Why is it possible to pass `null` in Map<String...
# getting-started
h
Why is it possible to pass
null
in Map<String, String>.get(null):
mapOf<String, String>("f" to "f").get(null as String?)
r
Interesting - you're actually calling an extension function with its own type parameters:
Copy code
public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.get(key: K): V? =
    @Suppress("UNCHECKED_CAST") (this as Map<K, V>).get(key)
So you're doing an unchecked cast from
Map<String, String>
to
Map<String?, String>
e
the Kotlin interface
Map<K, out V>
is invariant in
K
, but Java's interface defines (effectively)
fun containsKey(Any?)
and
fun get(Any?)
. and it kind of makes sense that
containsKey(!is K) == false
and
get(!is K) == null
r
It doesn't permit
mapOf("f" to "f").get(1)
, though, that's a compile error, though it would work in Java. Presumably because there are no occasions when it could possibly return anything. I guess that a key with type
String?
might be a
String
so might be able to be a key to an entry in a
Map<String, String>
, so it makes sense to accept it to that
get
extension function rather than force the caller to do
mightBeNull?.let { notNull -> mapWithNotNullKeys[notNull] }
.
e
the Kotlin compiler also rejects
"f" == 1
while it accepts
"f" == null
, so it is consistent