Sunday, 17 August 2014

Scala Note 8: Immutable Object v.s. Mutable Object

1. Immutable objects are often easier to reason about than mutable ones, because they do not have complex state spaces that change over time.

2. You can pass immutable objects around quite freely, whereas you may need to make defensive copies of mutable objects before passing them to other code.

3. There is no way for two threads concurrently concurrently accessing an immutable to corrupt its state once it has been properly constructed, because no thread can change the state of an immutable.

4. Immutable objects make safe hash table keys. If a mutable object is mutated after it is placed into a HashSet, that object may not be found the next time you look into the HashSet.

5. Immutable object sometimes require a large object graph be copied where otherwise an update could be done in place.

For example, 
val array: Array[String] = new Array(5)
array(0) = "Hello"

Scala is like Java in that most variables are actually references to heap-allocated objects. Hence, the array reference cannot be changed to point to a different Array, but the array elements themselves are mutable, so the elements can be modified.

Both val and var must be initialized. 

The var and val keywords only specify whether the reference can be changed to refer to a different object(var) or not (val). They don't specify whether or not the object they reference is mutable.

No comments:

Post a Comment