【发布时间】:2021-04-13 21:54:49
【问题描述】:
当我运行这段代码时,我得到一个Type mismatch: inferred type is kotlin.collections.HashMap<String, Int> /* = java.util.HashMap<String, Int> */ but kotlin.collections.HashMap<String, Any?> /* = java.util.HashMap<String, Any?> */ was expected 错误
data class Record(
var blah: HashMap<String, Any?>
)
fun test2() {
val data2 = hashMapOf("key" to 10000)
val a = Record(data2)
println(a.blah)
}
在 Kotlin Playgrounds 上运行上述代码:https://pl.kotl.in/vL2n_Qrwo
只有当数据类中的类型是 HashMap 时我才会得到这个错误,当它只是一个 Map (https://pl.kotl.in/f1V3Eeyj-) 时我不会得到它。为什么是这样?通过明确指定 Any? (任何带有问号,以指定它可以为空)在 hashMapOf 类型中所以hashMapOf<String, Any?>("key" to 10000)
最奇怪的是,如果我不创建一个新变量data2 来保存哈希图,它不会返回任何错误!
data class Record(
var blah: HashMap<String, Any?>
)
fun test1() {
val a = Record(hashMapOf("key" to 10000))
println(a.blah)
}
在 Kotlin Playgrounds 上运行这个:https://pl.kotl.in/K12q1Bd7B
如您所见,没有错误。这对我来说毫无意义。
【问题讨论】: