将不可变转换为可变集合

时间:2010-07-05 09:30:04

标签: collections immutability scala-2.8 mutable

将collection.immutable.Set转换为collection.mutable.Set?

的最佳方法是什么?

2 个答案:

答案 0 :(得分:19)

scala> var a=collection.mutable.Set[Int](1,2,3)                              
a: scala.collection.mutable.Set[Int] = Set(1, 2, 3)

scala> var b=collection.immutable.Set[Int](1,2,3)
b: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> collection.mutable.Set(b.toArray:_*)      
res0: scala.collection.mutable.Set[Int] = Set(1, 2, 3)

scala> collection.mutable.Set(b.toSeq:_*)  
res1: scala.collection.mutable.Set[Int] = Set(1, 2, 3)

scala> collection.mutable.Set(b.toList:_*)
res2: scala.collection.mutable.Set[Int] = Set(1, 2, 3)

答案 1 :(得分:0)

通过.to(factory)所应用的工厂建造者来开始Scala 2.13

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

Scala 2.13之前并以Scala 2.10开头:

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