为什么 Kotlin 不能使用可为空值类型推断此 HashMap 的类型?

geo*_*sey 2 java hashmap kotlin

当我运行此代码时,出现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)
}
Run Code Online (Sandbox Code Playgroud)

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

在 Kotlin Playgrounds 上运行这个:https : //pl.kotl.in/K12q1Bd7B

如您所见,没有错误。对我来说完全是无稽之谈。

And*_*eas 6

推理引擎一次只分析一个语句。

现在的问题是关于两个类型参数的推论fun <K, V> hashMapOf(): HashMap<K, V>,即类型KV

在第一个示例中,val data2 = hashMapOf("key" to 10000)对 的结果没有要求hashMapOf(),因此引擎使用该参数来确定这两种类型。"key" to 10000是一对Stringto Int,所以结果是KisStringVis Int

在第二示例中,val a = Record(hashMapOf("key" to 10000))中,Record构造需要,通过返回的对象的类型hashMapOf() 必须是一个对象,它是与分配兼容HashMap<String, Any?>。因此推理引擎使用KasStringVas Any,并且编译接受它,因为"key"与 兼容String并且10000兼容Any?