https://kotlinlang.org logo
Title
y

y

04/25/2023, 2:07 PM
why does
Map<K, V>.get(key)
work for
key == null
? how does it even typecheck?
a

Adam S

04/25/2023, 2:17 PM
are you asking about JVM interop? https://stackoverflow.com/a/74707052/4161471
e

ephemient

04/25/2023, 2:17 PM
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

y

04/25/2023, 2:22 PM
@ephemient so... since
K
is covariant to
K?
?
j

Joffrey

04/25/2023, 2:39 PM
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

y

04/25/2023, 2:40 PM
oh, so it's because
Map<K, V>
is covariant to
Map<K?, V>
?
(probably not so apologies in advance heh)
e

ephemient

04/25/2023, 2:41 PM
Map
is not naturally covariant in
K
but the
get
extension is explicitly on
out K
j

Joffrey

04/25/2023, 2:50 PM
@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

y

04/25/2023, 2:52 PM
I believe I understand now. thank you for the explanation! as for "to" vs "in" - I was going by the wikipedia article
e

ephemient

04/25/2023, 6:04 PM
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?
s

Stephan Schröder

04/26/2023, 8:00 AM
hmm, i would have assumed, it's because K isn't restricted explicitly, it's implicitly restricted to
K: Any?