Saturday, October 1, 2011

Immutable Objects and val Variables Are Not the Same Thing in Scala

In Scala programs, some objects may be mutable, others immutable. A mutable object's state can be changed. An immutable object's state cannot be changed.

Listing 1 - A Mutable Object

object Example1 extends Application {
    val aList = scala.collection.mutable.Set(1, 2, 3)
    println(aList)
    
    aList.add(4)
    println(aList)
}

In Listing 1, we create a mutable Set object with 3 elements (viz 1, 2, and 3) in it. Then, add a new element, 4, to it. Run the program, it will display:

Set(2, 1, 3)
Set(2, 1, 4, 3)

Obviously, we can change the state of the mutable Set object. If instead, we create an immutable Set object, for example, with the following statement
 
val aList = scala.collection.immutable.Set(1, 2, 3)

We won't be able to add a new element into that Set object. Accordantly, there is not the add method for the immutable Set class. (The + method will create a new Set object rather than add a new element into the original set).

In Scala programs, an variable may be a var or val variable. An variable holds a reference to an object. An var variable can be re-assigned to reference another object. A val variable cannot be re-assigned.


Listing 2 - val Variable Cannot Be Re-Assigned

object Example1 extends Application {
    val aList = scala.collection.mutable.Set(1, 2, 3)
    aList = scala.collection.mutable.Set(1, 2, 3, 4)
}

When we compile the program in Listing 2. Scala compiler will complain: reassigment to val. If we change val to var as in Listing 3, the program will compile fine.

Listing 3 - var Variable Can Be Re-Assigned

object Example1 extends Application {
    var aList = scala.collection.mutable.Set(1, 2, 3)
    aList = scala.collection.mutable.Set(1, 2, 3, 4)
}

Notice that in Listing 1, even aList is a val variable, we can change the state of the object referenced by it since the object is a mutable object.

Even though both immutable and val are about somethings that cannot be changed, one is about the object states, another objects referenced. They are indeed totally different. However, beginner Scala programers may get confused.

No comments: