When I run this code, I get a 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 error
data class Record(
var blah: HashMap<String, Any?>
)
fun test2() {
val data2 = hashMapOf("key" to 10000)
val a = Record(data2)
println(a.blah)
}
Run the above on Kotlin Playgrounds: https://pl.kotl.in/vL2n_Qrwo
I only get this error when the type in the data class is a HashMap, I don't get it when it's just a Map (https://pl.kotl.in/f1V3Eeyj-). Why is this? It's fixed by explicitly specifying Any? (Any with a question mark, to specify that it's nullable) in the hashMapOf type so hashMapOf<String, Any?>("key" to 10000)
The weirdest thing is if I don't create a new variable data2 to hold the hashmap, it doesn't return any error!
data class Record(
var blah: HashMap<String, Any?>
)
fun test1() {
val a = Record(hashMapOf("key" to 10000))
println(a.blah)
}
Run this one on Kotlin Playgrounds: https://pl.kotl.in/K12q1Bd7B
As you can see, no errors. It makes no sense to me.