Ellen Spertus
11/27/2023, 1:16 AMnull
as a second argument to Map.getOrDefault()
works:
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:
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?ephemient
11/27/2023, 1:29 AMephemient
11/27/2023, 1:30 AMMap<K, out V>
is covariant in V
, Map<K, V>
is a Map<K, V?>
ephemient
11/27/2023, 1:32 AMephemient
11/27/2023, 1:32 AMgetOrDefault()
which is a Java default interface method, not the Kotlin extension getOrElse()
ephemient
11/27/2023, 1:32 AMEllen Spertus
11/27/2023, 1:32 AMgetOrElse()
.ephemient
11/27/2023, 1:34 AMgetOrElse
is completely happy to use a supertype for reasons I mentioned before that