Kotlin Basics: Val

Kotlin, like Scala, introduces a concept of value (instead of only variable.) In Kotlin (and Scala) using the val keyword to define a value, makes it final. By final, the value it was given can not be reassigned. Practice wise, Kotlin developers are encouraged to use val’s for the most part, and variables only as specifically needed.

Fo for example:

val nochange = 3

If we try and later reassign nochange to 4, an error will be returned:

error: val cannot be reassigned

Using var is the appropriate method of setting variables that will change. If we had a variable that stored a score for a game, that variable will certainly change over time. It’s not a final value, so we use syntax like:

var highScore = 230109

This could be reassigned again with new values, like:

highScore = 240887

Final Variables (Java)

In Java this is done using the final keyword:

final double constantValue = 7.65;

Why Val over Var?

Why crate immutable (non changing) values, instead of variables? This is answered at ProAndroidDev by Nick Skelton. Suffice to say, that when variables are used we can hit problems of race conditions, as well as corrupted states.

The value in question was updated to a state that it shouldn’t be able to update. Nick gives a great example of how even Java’s final variable option doesn’t quite get there.

He shows some code where you have two classes Age and Student. In the age class all data is using variables. Student, however, uses the final keyword to set immutable data.

However, even though the Student class uses final variables, we can still reassign values to those very same final variables. In Nick’s example, only the reference to the variable is final. So while he could block student.age = new Age(), he could still do student.age.month = newValue. Check out his code example for more info.

If we use immutable objects as the norm and variables as the exception, then the code will have less problems with state. Objects will be thread safe, we’ll no longer have issues with race conditions and less concurrency issues.

Downsides of Immutability

The downside of using immutable objects, is that it requires more creation (less reassignment) and therefore more memory.

This downside is often dismissed though as most applications wouldn’t impact memory enough, for this argument to be considered. I suppose though, that perhaps a thin client with limited memory, using a data type that is quite large, might create a problem. But I say *might* as I really don’t know. I just don’t have that expertise.

More Info on Immutability

For more information on immutability, check out the video below from Robert C Martin (on the topic of Functional Programming.)

Leave a Reply

Your email address will not be published. Required fields are marked *