val
and var
scala> val a = 123
a: Int = 123
scala> a = 456
<console>:8: error: reassignment to val
a = 456
scala> var b = 123
b: Int = 123
scala> b = 321
b: Int = 321
val
references are unchangeable: like a final
variable in Java
, once it has been initialized you cannot change itvar
references are reassignable as a simple variable declaration in Java val mut = scala.collection.mutable.Map.empty[String, Int]
mut += ("123" -> 123)
mut += ("456" -> 456)
mut += ("789" -> 789)
val imm = scala.collection.immutable.Map.empty[String, Int]
imm + ("123" -> 123)
imm + ("456" -> 456)
imm + ("789" -> 789)
scala> mut
Map(123 -> 123, 456 -> 456, 789 -> 789)
scala> imm
Map()
scala> imm + ("123" -> 123) + ("456" -> 456) + ("789" -> 789)
Map(123 -> 123, 456 -> 456, 789 -> 789)
The Scala standard library offers both immutable and mutable data structures, not the reference to it. Each time an immutable data structure get "modified", a new instance is produced instead of modifying the original collection in-place. Each instance of the collection may share significant structure with another instance.
Mutable and Immutable Collection (Official Scala Documentation)