scala> import scala.collection.mutable.LinkedHashSet
import scala.collection.mutable.LinkedHashSet
scala> val set1 = new LinkedHashSet[Int]
val set1: scala.collection.mutable.LinkedHashSet[Int] = LinkedHashSet()
scala> set1 += 1
val res0: set1.type = LinkedHashSet(1)
scala> val set2 = LinkedHashSet.from(set1)
val set2: scala.collection.mutable.LinkedHashSet[Int] = LinkedHashSet(1)
scala> set1 += 2
val res1: set1.type = LinkedHashSet(1, 2)
scala> set2
val res2: scala.collection.mutable.LinkedHashSet[Int] = LinkedHashSet(1, 2)
Problem
Typically factory method from in mutable collections constructs new collection with given elements (e.g. ArrayBuffer.from[T]). However, for LinkedHashSet and LinkedHashMap method from reuses the argument if it is of the same type:
object LinkedHashSet extends IterableFactory[LinkedHashSet] {
def from[E](it: collection.IterableOnce[E]) =
it match {
case lhs: LinkedHashSet[E] => lhs
case _ => Growable.from(empty[E], it)
}
This is confusing and unexpected given that other mutable collections always return new collections.
Reproduction steps
Scala version: 2.13.10
Problem
Typically factory method
from
in mutable collections constructs new collection with given elements (e.g.ArrayBuffer.from[T]
). However, forLinkedHashSet
andLinkedHashMap
methodfrom
reuses the argument if it is of the same type:This is confusing and unexpected given that other mutable collections always return new collections.