https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

Ellen Spertus

11/27/2023, 1:16 AM
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

ephemient

11/27/2023, 1:29 AM
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

Ellen Spertus

11/27/2023, 1:32 AM
I'm happy to switch to
getOrElse()
.
e

ephemient

11/27/2023, 1:34 AM
getOrElse
is completely happy to use a supertype for reasons I mentioned before that