How does one convert a Scala Array
to a m开发者_如何学编程utable.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
.
scala> val s=scala.collection.mutable.Set()++Array(1,2,3)
s: scala.collection.mutable.Set[Int] = Set(2, 1, 3)
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.
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)
精彩评论