scala / scala-library-next

backwards-binary-compatible Scala standard library additions
Apache License 2.0
69 stars 17 forks source link

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

Open erikvanoosten opened 1 year ago

erikvanoosten commented 1 year ago

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)) }
}
ritschwumm commented 1 year ago

the java method uses a lot of magic null values which is something scala tries to avoid. how would the signature look in terms of Option?

and, since i can't remember ever having needed something like this: can you give an example where this method is useful?

erikvanoosten commented 1 year ago

the java method uses a lot of magic null values which is something scala tries to avoid. how would the signature look in terms of Option?

The whole point of merge is that options are not needed. My proposal is to not allow null arguments at all.

and, since i can't remember ever having needed something like this: can you give an example where this method is useful?

In zio-kafka we need to merge offsets, something like Map[Partition, Long] where we keep the largest offset per partition. The discussion (with code) that sparkled this issue is at https://github.com/zio/zio-kafka/pull/1079