e

    elect

    11 months ago
    what about changing on
    Map<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 else
    e

    ephemient

    11 months ago
    you mean
    (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 signature
    e

    elect

    11 months ago
    yeah, that
    r

    Roukanken

    11 months ago
    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:
    public inline fun <K, V> Map<K, V>.getOrElseWithKey(key: K, defaultValue: (K) -> V): V = 
        this.getOrElse(key) { defaultValue(key) }
    e

    elect

    11 months ago
    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

    11 months ago
    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

    11 months ago
    too much noise compared to save the key in a local property 😕
    e

    ephemient

    11 months ago
    from stdlib:
    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
    public fun <K, V> K.getAmong(vararg maps: Map<K, V>) = maps.firstNotNullOfOrNull { it[this] }
    j

    jimn

    11 months ago
    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

    11 months ago
    definitely longer than the name. 48 bytes of bytecode emitted for the most trivial case, I tested.
    j

    jimn

    11 months ago
    @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.