Kotlin for Beginners: Immutability and the Value of ‘val’
What is immutability? Why is immutability valuable? What does immutability have to do with Kotlin?
What does Immutable mean?
By definition, immutable means that, once created, an object/variable can’t be changed. So, instead of changing a property of an object, you have to make a copy (or clone) of the entire object and in the process, change the property in question.
Lets look at some Java examples. Here we have Age
which is mutable because the properties of Age can be changed (ie. mutated) willy nilly. Note the setters. Setters are a dead give-away that a class is mutable.
Now take a look at Student:
Student has no setters, so far so good. All its properties are final
, bonus points. This is pretty clean code and a nice looking class. But is it Immutable?
Not quite.
Consider the code for creating a Student
:
So in which month was nick
born? 1, 3 or 8?
If Student
is immutable, then the answer should be 1, because nick
was created with testAge
and at the time of creation, testAge
had a property month
set to 1. However, in this case, both testAge
and nick.getAge()
have the ability to mutate Student.
Even though nick.age
is final
, only the reference is final
. This prevents you from doing something like nick.age = new Age()
but not from doing this nick.age.month = 4
.
To prevent mutation, we have two choices: make Age
immutable by removing the setters; or make Student immutable by copying Age
like so:
This pattern of cloning for immutability is almost unheard of in the Java world. It’s very verbose and feels wrong. Making Age
immutable is clearly a nicer alternative, but not always possible.
At first, cloning like this might seem like a crazy idea. This will just chew up memory, and for what benefit? Well in terms of technical pro’s and con’s, there are really only two, both for and against:
For Immutability
Immutable objects are thread safe. No race conditions, no concurrency problems, no need to sync.
I work mainly in Android, with two threads (UI and background) who, (because I try to write clean code) generally stay out of each other’s way. While Thread Safety is an interesting and important topic, it’s one that rarely stings me.
Against Immutability
As you have seen, writing immutable code can mean cloning, cloning involves object creation and extra memory.
But unless you are working with large data structures, and copying them 1000s of times a second, and leaking said objects in memory, garbage collection should have you covered, even on a mobile device.
…two pretty weak arguments both for and against. So what is the benefit of Immutability?
Why Mutable?
Why do we write mutable code?
Mutable code is far more prolific because it comes to us humans naturally. The world around us is filled with mutable objects, so our brain finds it easier to work within this construct. It is easier for us to comprehend an object with many changeable properties, each of which can change when actions are performed on them. When we don’t like the colour of our car, we don’t go and create a new car, we change the colour of the car by painting it. We don’t create a new bank account each time we make a deposit, we change the balance. Because we all grew up drinking the Object Oriented Kool-Aid, we tend to model our code on the real world. It makes sense deep inside. Gives us warm fuzzy feelings.
Just tell me already… why Immutability?
Immutability is an idea whose fanbase comes out of Functional Programming languages like Haskell where variables simply do not exist. Everything is immutable and the idea of a pure function is the holy grail. This experiment yielded interesting benefits and explores a radically different paradigm in software development: Immutable by default, mutable by exception.
Because you are forced to copy your objects each time you want to make a change, it makes you much more conscious of HOW and WHEN you change your application’s state. The benefits of immutability lies with reducing the possible states within your app. Charles Scalfani with his article on limits explains this in a way we can all understand:
Did you ever wonder why most solutions to program glitches are fixed by rebooting your computer or restarting the offending application? That’s because of state. The program has corrupted its state.
The Value of Val
So how does Kotlin help encourage less state and more immutable code?
TL;DR prefer val
over var
Kotlin, the language itself, encourages developers to write immutably, by encouraging you to use val
. The result is code that literally looks cleaner.
Using vals in your code makes you think about alternative, immutable, functional code. […] Removing vars leads to refactoring. The refactoring leads to new coding patterns. New coding patterns leads to a shift in your approach to programming. This shift in approach leads to transformative code that has fewer defects and is easier to maintain.
— Beginning Scala, David Pollack
I’m not sure if it was a coincidence or not, but I find that if you start to write bad code in Kotlin, the code literally starts to look bad. Here’s a little cheat sheet to post on your computer:

Using var
is not forbidden, nor is !!
or ?
. But coming from Java, you will want to use them all the time. Resist and you will be rewarded! Using val
requires a bit of a shift in understanding, a decent amount of refactoring and this can take time, but trust me, it is worth the trouble.
Consider the following Kotlin equivalents of the above Java code:
Notice all the !! and ?
in there? Everything from line 16 should not be possible. Lets try it again.
This is the holy grail of immutable classes in Kotlin. val
everywhere means that the code that uses these models is super clean and can safely assume that the properties will never change and that they are not null. Allowing you to just get on with the job at hand.
Further reading: