Scala collections mismatch 2.8?

Why are the transform methods (version for mutation in-place map ) and retain (version for mutation in-place filter ) defined only on mutable.Map , but not on mutable.Buffer and mutable.Set ? shouldn't all mutable collections support these methods?

+7
scala scala-collections
source share
1 answer

The retain and transform Map operations are about keys and values , concepts that are not part of Set or Buffer .

A map is an iteration consisting of key pairs and values ​​(also called mappings or associations).
Fundamental operations on maps are similar to operations on sets.

But your operations are listed in:

Mutable maps additionally supports the operations shown in the following table.

 ms transform f 

Converts all related values ​​to map ms with function f .

 ms retain p 

Saves only those mappings in ms that have key satisfying the predicate p .


one-zero-zero-one comments:

retain and transform are essentially mutations in place of filter and Map respectively, and can be easily defined on Set and Buffer .
I don’t see how Map specific they are.

I would say that retain and transform offer Map-specific implementations (in the sense that their implementation specifically deals with keys and values) for functions like Map and filter from TraversableLike .

Implementing transform in Set and Buffer will add little value, as it simply shrinks to Map .


Note: Michael Kebe comments:

One more thing. immutable.MapLike has a transform method, but not a retain method.

(unlike mutable.MapLike , which has both)

This is similar, however, according to the nature of the conversion operations , if transform creates a new map by filtering and transforming the bindings of an existing map.

Here is the source code to convert

 def transform[C, That](f: (A, B) => C)(implicit bf: CanBuildFrom[This, (A, C), That]): That = { val b = bf(repr) for ((key, value) <- this) b += ((key, f(key, value))) b.result } 

The source code for retain , however, has changed the current instance, which can only be compatible with Mutable objects:

 /** Retains only those mappings for which the predicate * `p` returns `true`. * * @param p The test predicate */ def retain(p: (A, B) => Boolean): this.type = { for ((k, v) <- this ; if !p(k, v)) this -= k this } 
+8
source share

All Articles