在 Scala 中将可变集合转换为不可变集合

Convert a mutable collection to an immutable collection in Scala

是否有一种通用的方法可以将 Scala 中的一些可变集合转换为其对应的不可变集合(假设它有一个)?

示例用例...

private[this] val _collection: mutable.TreeSet[A]

def collection: immutable.TreeSet[A] = {
  // convert mutable _collection to immutable version for public consumption
}

我尝试了以下...

def collection: immutable.TreeSet[A] = {
  _collection.to[immutable.TreeSet[A]]
}

...但这导致编译时出现神秘错误消息...

scala.collection.immutable.TreeSet[A] takes no type parameters, expected: one

...有什么想法吗?

我怀疑 immutable.TreeSet 必须从头开始创建:

  trait Aaa[A] {
    val _collection: mutable.TreeSet[A]

    def collection: immutable.TreeSet[A] = {
      immutable.TreeSet.empty[A] ++ _collection
    }
  }

编辑 跟进评论

来自immutable.TreeSet的scala-2.11.7源码:

import scala.collection.immutable.{RedBlackTree => RB}

private def newSet(t: RB.Tree[A, Unit]) = new TreeSet[A](t)

不幸的是 newSet 是私有的并且来自 mutable.TreeSet:

class TreeSet[A] private (treeRef: ObjectRef[RB.Tree[A, Null]], from: Option[A], until: Option[A])

构造函数也是私有的...

如果您不关心最终得到的特定 Set 实现,那么只需 val immutableSet = mutableSet.toSet

如果您确实想要不可变的 TreeSet,而不仅仅是任何 Set,您将需要使用 breakOut:

val immutableSet: immutable.TreeSet[T] = mutableSet.map(identity)(collection.breakOut)