A HashMap is not a Map?


I thought this would work. Should it?

  val m: java.util.Map<String, Any> = java.util.HashMap<String, Any>()

It gives this error:

  Error:(21, 44) Kotlin: Type mismatch: inferred type is java.util.HashMap<kotlin.String, kotlin.Any>
                          but java.util.Map<kotlin.String, kotlin.Any> was expected

Kotlin version 0.8.11.



I think, the compiler warns you against using java.util.Map: if you use kotlin.Map (or MutableMap) instead, it will work fine


Okay, the error is gone. This seems like magic... is the magic explained somewhere? I looked at the reference doc for kotlin.Map and MutableMap and it's not inherting from java.util.Map. Are these types like aliases, or ?  I can't assign one to a java.util.Map variable, but I can pass it to a java function that takes java.util.Map as a parameter. Usually those two things work the same.



Some explanation is available here: http://blog.jetbrains.com/kotlin/2012/09/kotlin-m3-is-out/

In short, Java’s Map is mutable, and in Kotlin we replace it with a pair of interfaces (read-only) Map and MutableMap to facilitate better type safety. If these extended Java’s Map, they’d have to be mutable as well.