I'll just add: corelibs-dev is the right place for this discussion, not amber-dev.

On 10/16/2025 11:05 PM, Ethan McCue wrote:
I don't have anything intelligent to add, but I assume either

* It's a good / okay idea, not high priority
* putIfAbsent and computeIfAbsent are seen to be enough for lazy operations * Something much more subtle and/or annoying about how it will affect the universe of map implementations.

Either way, just so there is something concrete to talk about:

import module java.base;

public final class Maps {
    private Maps() {
    }

    private static final Object DEFAULT = new Object();

    @SuppressWarnings({"unchecked","rawtypes"})
    public static <K, V> V getOrCompute(
            Map<K, ? extends V> m,
            Object key,
            Function<? super K, ? extends V> compute
    ) {
        Object value = ((Map) m).getOrDefault(key, DEFAULT);
        if (value == DEFAULT) {
            return compute.apply((K) key);
        }
        else {
            return (V) value;
        }
    }
}

(Note the three needed casts - this might be difficult for the same reason Map#gettakes an Objectand not a K)

On Thu, Oct 16, 2025 at 7:20 PM Chris Bouchard <[email protected]> wrote:

    Alberto,

    I believe your getOrPut methods already exist as putIfAbsent and
    computeIfAbsent, unless I'm missing a subtle difference.

    On Thu, Oct 16, 2025, 14:20 Alberto Otero Rodríguez
    <[email protected]> wrote:

        Also, other two new methods might be interesting if you want
        to get a value from a map, but if the key doesn't exist you
        want to insert that value in the map and return it:

        default V getOrPut(Object key, V defaultValue)

        default V getOrPut(Object key,  Function<? super K, ? extends
        V> defaultValueFunction)


    Chris

Reply via email to