scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

Unexpected behavior of LinkedHashSet.from[T] and LinkedHashMap.from[T] #12766

Closed liontiger23 closed 1 year ago

liontiger23 commented 1 year ago

Reproduction steps

Scala version: 2.13.10

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.

SethTisue commented 1 year ago

@scala/collections ?