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.

3 Answers 3

20
scala> val s=scala.collection.mutable.Set()++Array(1,2,3)
s: scala.collection.mutable.Set[Int] = Set(2, 1, 3)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

14

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.