In Kotlin, ‘val‘ and ‘var‘ are keywords used for declaring variables. The difference between them is that ‘val‘ is immutable, which means that its value cannot be changed once assigned. On the other hand, ‘var‘ is mutable and its value can be reassigned.
Let’s consider an example:
val x = 5
var y = 10
In this example, ‘x‘ is assigned the value of ‘5‘, and since it is declared as a ‘val‘, its value cannot be changed later in the program. However, ‘y‘ is assigned the value of ‘10‘, and since it is declared as a ‘var‘, its value can be changed later in the program.
y = 15
Now ‘y‘ will have a new value of ‘15‘.
The advantage of using ‘val‘ wherever possible is that it helps in achieving immutability and hence, reduces the risk of unexpected changes to the variables. This helps in making the code more robust, easier to read, and maintainable.
In summary, if we want to declare a variable which can be reassigned, then we use ‘var‘. However, if we want to declare a variable whose value should remain the same throughout the program, then we use ‘val‘.