开发者

Convert an array to a mutable set in Scala?

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜