what about changing on `Map<K, V>` the `getO...
# stdlib
e
what about changing on
Map<K, V>
the
getOrElse
by passing as argument the key which wasn't found?
Copy code
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V
to
Copy code
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: (V) -> V): V
My use case is to search for the same key somewhere else
e
you mean
(K) -> V
? that would be a breaking change, note how
Copy code
val map = mapOf(3 to "fizz", 5 to "buzz", 6 to "fizz", 9 to "fizz", 10 to "buzz")
repeat(10) { println(map.getOrElse(it + 1) { (it + 1).toString() }) }
works now and wouldn't with your proposed signature
e
yeah, that
r
do you really need that? Since you already have they key when you are calling the method... The only reason I can think of is, you want to call already defined method for the default value, but you could easily just wrap it with lamda in place you can fairly easily implement this wrapping automatically too:
Copy code
public inline fun <K, V> Map<K, V>.getOrElseWithKey(key: K, defaultValue: (K) -> V): V = 
    this.getOrElse(key) { defaultValue(key) }
e
we are talking about convenience here
do I really need that? No, but it'd be comfortable to have it passed as an arg
j
Copy code
public fun<K,V>  K.getAmong(vararg maps:Map<K,V>)=maps.firstOrNull{it.containsKey(this)}?.get(this)

val defaultVal="default thing"
val firstChoice="the best key"
val solveUseCase=firstChoice.getAmong(map1,map2,map3)?:defaultVal
e
too much noise compared to save the key in a local property 😕
e
from stdlib:
Copy code
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue()
so your chained lookup is entirely equivalent to
Copy code
public fun <K, V> K.getAmong(vararg maps: Map<K, V>) = maps.firstNotNullOfOrNull { it[this] }
j
fNNOON is comically out of control source code signalling baked into the symbol. the function name is probably longer than the emitted instructions. 🙄
e
definitely longer than the name. 48 bytes of bytecode emitted for the most trivial case, I tested.
j
@ephemient what nm tool shows bytes on a method? this is not shown in the bytecode viewer. good catch that a key that points to null may prevent the same key later in the list not pointing to nulls.