Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Friday, May 25, 2012

Reference Immutatibility vs object immutability

It's important to understand the difference between immutability of reference and immutability of objects.
scala> class Car(brand:String, year:Int) {
     |      var fuelPercentage = 20
     |      def getBrand() = brand
     |      def getYear() = year
     |      def fillTank(): Unit = fuelPercentage = 100
     |      def getFuelPercentage() = fuelPercentage
     |      override def toString = getBrand() + " from " + year
     | }
defined class Car

scala>

scala> val mycar = new Car("Citroen", 2011)
mycar: Car = Citroen from 2011

scala> mycar.getFuelPercentage()
res2: Int = 20

scala> mycar.fillTank()

scala> mycar.getFuelPercentage()
res4: Int = 100

scala> mycar = new Car("Audi", 2012)
:9: error: reassignment to val
       mycar = new Car("Audi", 2012)
             ^

scala> var hiscar = new Car("Audi", 2012)
hiscar: Car = Audi from 2012

scala> hiscar = new Car("Porsche", 2012)
hiscar: Car = Porsche from 2012

scala>

As you can see mycar is an immutable reference because we used the 'val' keyword. hiscar on the other hand is a mutable reference due to using the keyword 'var'.  Both car objects are mutable. We can fill the tank up and the fuelpercentage will change.

No comments:

Post a Comment