Hey! I am trying to understand how the type def of...
# getting-started
v
Hey! I am trying to understand how the type def of
getOrElse
works.
Copy code
fun foo(x: String) : () -> String  = { x + "!" }

val map = mapOf(Pair("a", 1), Pair("b", 2))
val result = map.getOrElse("x", foo("kotlin"))
I would expect a type-error here, but it happily returns a String. If I define the type of
result
it works as I would expect. Can someone help me understand the type definition of `orGetElse`:
Copy code
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue()
m
veiset: unrelated, but do you know that you can do
"a" to 1
, instead of creating a new
Pair
?
d
The
V
in
Map
is an
out
parameter, so really the signature is
public inline fun <K, V> Map<K, out V>.getOrElse...
v
Oh, I didn't know that Edson. That's pretty sweet. Thanks!
d
V
is inferred to be
Any
and then you have a
Map<K, out Any>
, which your map satisfies.
v
Oh. That makes sense. How do I see that the signature really is
Map<K, out V>
? Do I have to check the signature of
Map
?
Yup. You do.
d
Yes. Declaration-Site variance is the keyword here.
v
Thanks Take! Perfect, now I understand. Cheers. 😄