Mutable and Immutable
Data Types
Unit, corresponds to no value
Null, null or empty reference
Nothing, the subtype of every other type; includes no values
Any, the supertype of any type; any object is of type Any
AnyRef, the supertype of any reference type
Mutable and Immutable Reference
object Variables {
def main(args: Array[String]) {
var v : String = "Hello"; // mutable reference
val v2 : String = "Hello"; // immutable reference
var v3 = 10; // automatically decide data type
v = "World!"; // v can be reassigned to a different object
v = 10; //error, v cannot be reassigned to a different data type
v2 = "World!"; //error, v2 cannot be reassigned to a different object
}
}
Immutable Reference to a Immutable Object
class Person(val name: String) { // mutable fields
def getName(): String = {
s"$name"
}
}
object Demo {
def main(args: Array[String]) {
val p = new Person("Lin"); // immutable reference
println("Name: "+p.getName())
p.name = "Chen"; //error, not able to reassign the value
}
}
Immutable Reference to a Mutable Object
class Person(var name: String) { // mutable fields
def getName(): String = {
s"$name"
}
}
object Demo {
def main(args: Array[String]) {
val p = new Person("Lin"); // immutable reference
println("Name: "+p.getName())
p.name = "Chen";
println("Name: "+p.getName())
}
}
Reference