
Immutable reference (referential immutability) There are basically the following two types of immutability:
Now, that I’ve used the word referential immutability quite a few times, let us now inspect what it means and how many types of immutability there are.
We cannot have nullable data types with the const val properties as a result, we cannot have null values for the const val properties eitherĪs a result, the const val properties guarantee immutability of value but have lesser flexibility and you are bound to use only primitive data types with const val, which cannot always serve our purposes. We can have the val property of any type, be it our custom class or any primitive data type, but only primitive data types and String are allowed with a const val property. You cannot write delegates for the const val properties. We can have val properties anywhere in our Kotlin code, inside functions, as a class member, anywhere, but const val has to be a top-level member of a class/object. The val properties can have custom getters, but const val cannot. The val properties are read-only variables, while const val are compile time constants. Let’s discuss some of the differences between val and const val: You cannot assign the outcome (result) of a function to const val. While val properties are read-only variables, const val, on the other hand, are compile time constants. Just modify val myString with const val myString and you cannot implement the custom getter. So, how can we overcome this? How can we enforce immutability? The const val properties are here to help us. As a result, we broke the immutable behavior of a val property.
So, whenever we requested the myString property, count got incremented and, on the next request, we got a different value. On comment (2), we pre-incremented the value of count and added it after the value of the field value, myString, and returned the same from the getter. On comment (1), we declared a custom getter for the val property myString.
So, now, let us look into the code to understand such behavior. Have a look at the output first, then we will further look into the program:Īs you can see, the myString property, despite being val, returned different values every time we accessed it. In this program, we declared myString as a val property, but implemented a custom get function, where we tweaked the value of myString before returning it. Let’s have a look the following program will not compile: fun main(args: Array) ")//(3)