elect
10/13/2021, 6:01 PMMap<K, V>
the getOrElse
by passing as argument the key which wasn't found?
public inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V
to
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 elseephemient
10/13/2021, 6:07 PM(K) -> V
? that would be a breaking change, note how
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 signatureelect
10/13/2021, 6:08 PMRoukanken
10/14/2021, 7:09 AMpublic inline fun <K, V> Map<K, V>.getOrElseWithKey(key: K, defaultValue: (K) -> V): V =
this.getOrElse(key) { defaultValue(key) }
elect
10/14/2021, 7:10 AMelect
10/14/2021, 7:11 AMjimn
10/14/2021, 7:15 AMpublic 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
elect
10/14/2021, 10:39 AMephemient
10/14/2021, 10:39 PMpublic inline fun <K, V> Map<K, V>.getOrElse(key: K, defaultValue: () -> V): V = get(key) ?: defaultValue()
so your chained lookup is entirely equivalent to
public fun <K, V> K.getAmong(vararg maps: Map<K, V>) = maps.firstNotNullOfOrNull { it[this] }
jimn
10/15/2021, 12:12 AMephemient
10/15/2021, 1:06 AMjimn
10/15/2021, 3:06 AM