看看这段代码:
import Moves.*
import ReverseMoves.*
interface Move {
val opp : Move
}
enum class Moves(override val opp: Move) : Move {
U(U_),
R(R_),
L(L_),
D(D_),
F(F_),
B(B_),
}
enum class ReverseMoves(override val opp: Move) : Move {
U_(U),
R_(R),
L_(L),
D_(D),
F_(F),
B_(B),
}
val cornerMapping: Map<Move, IntArray> = mutableMapOf(
U to intArrayOf(1, 2, 4, 3),
R to intArrayOf(2, 6, 8, 4),
L to intArrayOf(1, 3, 7, 5),
D to intArrayOf(7, 8, 6, 5),
F to intArrayOf(3, 4, 8, 7),
B to intArrayOf(2, 1, 5, 6)
)
fun f() {
for (m in cornerMapping) {
cornerMapping.set(m.key.opp, m.value.reversed().toIntArray())
}
}
尝试编译此代码时出现以下错误:
t.kt:37:23: error: unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@InlineOnly public inline operator fun <K, V> MutableMap<Move, IntArray>.set(key: Move, value: IntArray): Unit defined in kotlin.collections
@InlineOnly public inline operator fun kotlin.text.StringBuilder /* = java.lang.StringBuilder */.set(index: Int, value: Char): Unit defined in kotlin.text
cornerMapping.set(m.key.opp, m.value.reversed().toIntArray())
^
我看不到为什么出现此错误,传递给set
的键和值的类型与为cornerMapping声明的键和值完全匹配。
答案 0 :(得分:4)
我想set
中没有定义方法Map
。您可以将cornerMapping
变量的类型更改为MutableMap
,它将起作用:
val cornerMapping: MutableMap<Move, IntArray> = mutableMapOf(
Moves.U to intArrayOf(1, 2, 4, 3),
Moves.R to intArrayOf(2, 6, 8, 4),
Moves.L to intArrayOf(1, 3, 7, 5),
Moves.D to intArrayOf(7, 8, 6, 5),
Moves.F to intArrayOf(3, 4, 8, 7),
Moves.B to intArrayOf(2, 1, 5, 6)
)
fun f() {
for (m in cornerMapping) {
cornerMapping[m.key.opp] = m.value.reversed().toIntArray()
}
}
这是因为Map
界面中的方法仅支持对地图的只读访问;通过MutableMap
界面支持读写访问。