Hey, can someone explain me why this compiles? ```...
# announcements
t
Hey, can someone explain me why this compiles?
Copy code
fun foo () {
        val map: NavigableMap<String, String> = TreeMap()
        map["key"] = null
    }
d
My guess is:
NavigableMap
is a Java class and thus the types become flexible
c
My guess is because the
set
operator is inlined to
.put
, and
NavigableMap
is a Java interface so that
.put
uses platform typing with no null-safety. If you replace
NavigableMap
with
MutableMap
, it works as you’d expect
m
It’s because NavigableMap is a Java class. Kotlin has relaxed null checks for platform types. https://kotlinlang.org/docs/java-interop.html#null-safety-and-platform-types
But that means that I have a follow-up question: Why does this code not compile?
Copy code
import java.util.*

fun foo () {
    val map = TreeMap<String, String>()
    map["key"] = null
}
t
Ha funny didn't realize that. good catch! So i guess that disproved the explanation around platform types?
m
No, but apparently Kotlin has some special rules when it infers the type as opposed to when you set it explicitly.