14

How does one convert a Scala Array to a mutable.Set?

It's easy to convert to an immutable.Set:

Array(1, 2, 3).toSet

But I can't find an obvious way to convert to a mutable.Set.

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
schmmd
  • 18,650
  • 16
  • 58
  • 102

3 Answers3

20
scala> val s=scala.collection.mutable.Set()++Array(1,2,3)
s: scala.collection.mutable.Set[Int] = Set(2, 1, 3)
timday
  • 24,582
  • 12
  • 83
  • 135
14
scala> scala.collection.mutable.Set( Array(1,2) :_* )
res2: scala.collection.mutable.Set[Int] = Set(2, 1)

The weird :_* type ascription, forces factory method to see the array as a list of arguments.

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
13

Starting Scala 2.10, via factory builders applied with .to(factory):

Array(1, 2, 3).to[collection.mutable.Set]
// collection.mutable.Set[Int] = Set(1, 2, 3)

And starting Scala 2.13:

Array(1, 2, 3).to(collection.mutable.Set)
// collection.mutable.Set[Int] = HashSet(1, 2, 3)
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
Teodorico Levoff
  • 1,641
  • 2
  • 26
  • 44