veiset
07/10/2017, 11:28 AMgetOrElse
works.
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`:
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue()
menegatti
07/10/2017, 11:29 AM"a" to 1
, instead of creating a new Pair
?diesieben07
07/10/2017, 11:29 AMV
in Map
is an out
parameter, so really the signature is public inline fun <K, V> Map<K, out V>.getOrElse...
veiset
07/10/2017, 11:30 AMdiesieben07
07/10/2017, 11:30 AMV
is inferred to be Any
and then you have a Map<K, out Any>
, which your map satisfies.veiset
07/10/2017, 11:31 AMMap<K, out V>
? Do I have to check the signature of Map
?diesieben07
07/10/2017, 11:32 AMveiset
07/10/2017, 11:32 AM