为什么我收到此代码的“接收器类型不匹配”错误

sag*_*aga 1 generics types kotlin

看看这段代码:

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())
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译此代码时出现以下错误:

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())
                      ^
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会收到此错误,传递的键和值的类型与set为cornerMapping 声明的类型完全匹配。

Ser*_*gey 5

我想setMap. 您可以将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()
    }
}
Run Code Online (Sandbox Code Playgroud)

这是因为Map接口中的方法只支持对地图的只读访问;通过MutableMap接口支持读写访问。