What is the best way to convert collection.immutable.Set
to collection.mutable.Set
?
Asked
Active
Viewed 1.2k times
22

Xavier Guihot
- 54,987
- 21
- 291
- 190

barroco
- 3,018
- 6
- 28
- 38
2 Answers
21
scala> var a=collection.mutable.Set[Int](1,2,3)
a: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
scala> var b=collection.immutable.Set[Int](1,2,3)
b: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> collection.mutable.Set(b.toArray:_*)
res0: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
scala> collection.mutable.Set(b.toSeq:_*)
res1: scala.collection.mutable.Set[Int] = Set(1, 2, 3)
scala> collection.mutable.Set(b.toList:_*)
res2: scala.collection.mutable.Set[Int] = Set(1, 2, 3)

barroco
- 3,018
- 6
- 28
- 38
-
3Out of the three, which is better? – Jus12 Mar 18 '15 at 19:41
-
1This is one of the top Scala annoyances no doubt. – matanster Jul 05 '16 at 07:06
12
Starting Scala 2.13
, via factory builders applied with .to(factory)
:
Set(1, 2, 3).to(collection.mutable.Set)
// collection.mutable.Set[Int] = HashSet(1, 2, 3)
Prior to Scala 2.13
and starting Scala 2.10
:
Set(1, 2, 3).to[collection.mutable.Set]
// collection.mutable.Set[Int] = Set(1, 2, 3)

Xavier Guihot
- 54,987
- 21
- 291
- 190