davidrpugh
davidrpugh

Reputation: 4583

Convert a mutable collection to an immutable collection in Scala

Is there a generic way to convert some mutable collection in Scala to its immutable counterpart (assuming it has one)?

Example use case...

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

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

I tried the following...

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

...but that led to a cryptic error message on compilation...

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

...any thoughts?

Upvotes: 1

Views: 1016

Answers (2)

Dima
Dima

Reputation: 40510

If you don't care about the particular Set implementation you get in the end, the way to go is just val immutableSet = mutableSet.toSet

If you do specifically want immutable TreeSet, not just any Set, you will need to use breakOut:

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

Upvotes: 0

Filippo Vitale
Filippo Vitale

Reputation: 8113

I suspect the immutable.TreeSet has to be created from scratch:

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

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

EDIT to followup the comment

From the scala-2.11.7 source code of immutable.TreeSet:

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

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

Unfortunately newSet is private and from mutable.TreeSet:

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

The constructor is private too...

Upvotes: 2

Related Questions