schmmd
schmmd

Reputation: 19468

Convert an array to a mutable set in Scala?

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.

Upvotes: 14

Views: 5978

Answers (3)

Teodorico Levoff
Teodorico Levoff

Reputation: 1659

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)

Upvotes: 13

paradigmatic
paradigmatic

Reputation: 40461

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.

Upvotes: 14

timday
timday

Reputation: 24892

scala> val s=scala.collection.mutable.Set()++Array(1,2,3)
s: scala.collection.mutable.Set[Int] = Set(2, 1, 3)

Upvotes: 20

Related Questions