对于Set,Scala有可变和不可变两种类型,不过并非对于各种Set各提供可变与不可变两种类型,而是通过类继承的差别把可变性差异蕴含其中。
例如,
示例:
1. 不可变Set
scala> var s1=Set("1","2")
s1: scala.collection.immutable.Set[String] = Set(1, 2) #调用Set伴生对象的apply工厂方法创建了Set(1,2)对象
scala> s1+="3" #是s1=s1+"3"的简写,也可以是 s1=s1.+("3"),immutable.Set的+运算符将产生一个全新集
scala> s1
res15: scala.collection.immutable.Set[String] = Set(1, 2, 3)
scala> val s2=Set(1,2)
s2: scala.collection.immutable.Set[Int] = Set(1, 2)
scala> s2+=3
<console>:13: error: value += is not a member of scala.collection.immutable.Set[Int]
s2+=3
^
2. 可变Set
scala> val s3=scala.collection.mutable.Set(5,6)
s3: scala.collection.mutable.Set[Int] = Set(5, 6)
scala> s3+=7 #可以写成s3.+=(7),而不是s3=s3+7
res17: s3.type = Set(5, 6, 7)
scala> s3
res18: scala.collection.mutable.Set[Int] = Set(5, 6, 7)