why does `Map<K, V>.get(key)` work for `key ...
# getting-started
y
why does
Map<K, V>.get(key)
work for
key == null
? how does it even typecheck?
a
are you asking about JVM interop? https://stackoverflow.com/a/74707052/4161471
e
Copy code
operator fun <K, V> Map<out K, V>.get(key: K): V?
with
K = T?
,
Map<T, V>
is a
Map<out K, V>
Adam, that's not what was asked
y
@ephemient so... since
K
is covariant to
K?
?
j
The variance is not a property of
K
, but rather of the type using
K
. But what you can say is that
K
is a subtype of
K?
y
oh, so it's because
Map<K, V>
is covariant to
Map<K?, V>
?
(probably not so apologies in advance heh)
e
Map
is not naturally covariant in
K
but the
get
extension is explicitly on
out K
j
@y I think you're using "covariant" wrong. A generic type can be covariant in one of its type parameters, but a type being "covariant to" another type is not a thing. The declaration of the
get
operator allows you to use
Map<K,V>.get<K?, V>(nullableK)
because
Map<out K, V>
is covariant in its first type parameter
K
, which in turn means that
Map<K,V>
is a subtype of
Map<K?,V>
in this context.
y
I believe I understand now. thank you for the explanation! as for "to" vs "in" - I was going by the wikipedia article
e
K
is a subtype of `K?`: every inhabitant of
K
is also an inhabitant of
K?
Map<K, V>
is a subtype of
Map<out K?, V>
because
K
satisfies
out K?
because
K
is a subtype of
K?
❤️ 1
s
hmm, i would have assumed, it's because K isn't restricted explicitly, it's implicitly restricted to
K: Any?