Skip to content

Add mutable.Map.merge (similar to Java) #164

Open
@erikvanoosten

Description

@erikvanoosten

Please consider adding the merge method to mutable.Map. Java defines the method as follows, see java docs

/** If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key.

@param key - key with which the resulting value is to be associated
@param value - the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key
@param remappingFunction - the function to recompute a value if present
@returns the new value associated with the specified key, or null if no value is associated with the key
*/
def merge(key: K, value: V, remappingFunction: (V, V) => V): V

Rationale

When we never remove a value, using updateWith is very cumbersome and merge gives better readable code.

Translation to Scala

For discoverability and uniformity, the name could be changed to a variant of updateWith.

We don't do nulls in Scala so we shouldn't allow that. The return type would be Option.

The Scala implementation could be equivalent to:

def merge(key: K, value: V, remappingFunction: (V, V) => V): Option[V] = {
  this.updateWith(key) { v => v.map(remappingFunction(_, value).orElse(Some(value)) }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions