kotlin エラー「error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch:」の解決方法

kotlinで、エラー「error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch:」の解決方法を記述してます。読み取り専用の「mapof」で代入した値に対して変更処理を行った場合に発生します。
環境
- OS windows11 home
- java 17.0.2
- kotlin 1.7.20-release-201
エラー全文
以下のコードで発生。
fun main() {
val m = mapOf('a' to 1, 'b' to 2, 'c' to 3)
println(m) // {a=1, b=2, c=3}
println(m['a']) // 1
m['b'] = 5
}
エラーメッセージ
test.kt:9:5: error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun kotlin.text.StringBuilder /* = java.lang.StringBuilder */.set(index: Int, value: Char): Unit defined in kotlin.text
m['b'] = 5
^
test.kt:9:6: error: no set method providing array access
m['b'] = 5
^
原因
読み取り専用の「mapof」を使用した値を変更しようとしたため
対処法
「mutableMapOf」を使用する
fun main() {
val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3)
println(m) // {a=1, b=2, c=3}
println(m['a']) // 1
m['b'] = 5
println(m['b']) // 5
}
-
前の記事
javascript tableのtFoot要素を取得する 2022.11.01
-
次の記事
Flutter 背景色を指定する 2022.11.01
コメントを書く