https://kotlinlang.org logo
#stdlib
Title
# stdlib
e

elect

10/13/2021, 6:01 PM
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

ephemient

10/13/2021, 6:07 PM
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

elect

10/13/2021, 6:08 PM
yeah, that
r

Roukanken

10/14/2021, 7:09 AM
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

elect

10/14/2021, 7:10 AM
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

jimn

10/14/2021, 7:15 AM
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

elect

10/14/2021, 10:39 AM
too much noise compared to save the key in a local property 😕
e

ephemient

10/14/2021, 10:39 PM
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

jimn

10/15/2021, 12:12 AM
fNNOON is comically out of control source code signalling baked into the symbol. the function name is probably longer than the emitted instructions. 🙄
e

ephemient

10/15/2021, 1:06 AM
definitely longer than the name. 48 bytes of bytecode emitted for the most trivial case, I tested.
j

jimn

10/15/2021, 3:06 AM
@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.
21 Views