- var和val的区别很好理解,val类型的变量指的是引用不可更改,类似于java变量加了final修饰,但是引用对象内容可以改变
scala> val map = scala.collection.mutable.Map(1->"x", 2->"y")
map: scala.collection.mutable.Map[Int,String] = Map(2 -> y, 1 -> x)
//map变量不能再指向其他对象
scala> map = scala.collection.mutable.Map(1->"x", 2->"y")
<console>:12: error: reassignment to val
map = scala.collection.mutable.Map(1->"x", 2->"y")
^
scala> map += (3->"z")
res0: map.type = Map(2 -> y, 1 -> x, 3 -> z)
- mutable集合与immutable集合的区别也很好理解,mutable内容可以修改,而immutable集合初始化之后,内容是不能修改的
scala> val map = scala.collection.immutable.Map(1->"x", 2->"y")
map: scala.collection.immutable.Map[Int,String] = Map(1 -> x, 2 -> y)
scala> map += (3->"z") //修改内容会报错
<console>:13: error: value += is not a member of scala.collection.immutable.Map[Int,String]
map += (3->"z")
^
- 有一种情况如果将immutable集合定义为var类型的变量,内容是可以“修改”的
scala> var map = scala.collection.immutable.Map(1->"x", 2->"y")
map: scala.collection.immutable.Map[Int,String] = Map(1 -> x, 2 -> y)
scala> map += (3->"z") //并没有任何的错误
scala>
其实原来immutable对象的内容并没有改变,而是因为执行map += (3->"z")
之后在堆内存中又新建了一个对象,这时候的变量map的引用已经改变,指向了不同的对象,可以通过eq方法做个简单的验证
scala> var map = scala.collection.immutable.Map(1->"x", 2->"y")
map: scala.collection.immutable.Map[Int,String] = Map(1 -> x, 2 -> y)
scala> val original_map = map
original_map: scala.collection.immutable.Map[Int,String] = Map(1 -> x, 2 -> y)
scala> original_map eq map
res0: Boolean = true
scala> map += (3->"z")
scala> original_map eq map //引用已经改变
res2: Boolean = false
scala> println(original_map) //最初定义的immutable.Map内容并没有改变
Map(1 -> x, 2 -> y)
scala> println(map)
Map(1 -> x, 2 -> y, 3 -> z)