I don't understand why passing `null` as a second ...
# getting-started
e
I don't understand why passing
null
as a second argument to
Map.getOrDefault()
works:
Copy code
val greekLettersMap: Map<Char, String> = mapOf(
    'a' to "alpha",
    'b' to "beta",
    'g' to "gamma",
)
println(greekLettersMap['a'])
println(greekLettersMap['b'])
println(greekLettersMap.get('g'))
println(greekLettersMap.getOrDefault('c', null))
According to the documentation, this is the signature:
Copy code
open fun getOrDefault(
    key: K,
    defaultValue: @UnsafeVariance V
): V
Why is
null
acceptable as the second parameter when it's not part of the non-nullable type
Char
? Is that what
@UnsafeVariance
is permitting?
e
no
as
Map<K, out V>
is covariant in
V
,
Map<K, V>
is a
Map<K, V?>
call sites of extension functions are free to choose whichever type variables best suit the call, just like call sites of free functions
🙏 1
… is what I was going to say, but I just realized you're using
getOrDefault()
which is a Java default interface method, not the Kotlin extension
getOrElse()
so in this case "no, because of Java interop"
e
I'm happy to switch to
getOrElse()
.
e
getOrElse
is completely happy to use a supertype for reasons I mentioned before that