generics - 为什么我收到此代码的 'receiver type mismatch' 错误

标签 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())
    }
}

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

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 声明的类型完全匹配。

最佳答案

我猜Map中没有定义方法set。您可以将 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接口(interface)中的方法只支持对 map 的只读访问;通过 MutableMap 接口(interface)支持读写访问。

关于generics - 为什么我收到此代码的 'receiver type mismatch' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53809963/

相关文章:

java - 对泛型方法中的 Cast List 感到困惑?

haskell - 类型解构

python - Numpy 自动将字符串数组转换为数字数组

android - 一次性工作请求是否会干扰定期工作请求?

android - 如果值在OpenAPI生成器的Moshi中不匹配,如何退回枚举

java - Spring Boot @ConditionalOnMissingBean 和泛型类型

c# - 在编译时检查泛型参数

types - 我可以在 Object Pascal 的类中定义类型吗?

docker - 为什么用 "Not authoritative"响应我的 heroku 托管容器应用程序

java - ArrayList<T> 与 ArrayList<?>