Kotlin Tutorial – Val vs Var in Kotlin – We shall learn the difference between the usage of keywords val and var in Kotlin Programming Language with Example Kotlin programs.

 

Val vs Var in Kotlin

Let us first look into the actual names of these keywords and then we shall see how Kotlin Programming Language allows us to use these two keywords with examples.

Var – Variable – The object stored in the variable could change (vary) in time.

Val – Value – The object stored in val, could not vary in time. Once assigned the val becomes read only, like a constant in Java Programming language. The properties of the object (as Val) could be changed, but the object itself is read-only.\

 

Assign and change value of Var for a basic data type

We shall look into an example where we shall assign some data to val and var, and try to change the values they hold.

The value of a var could be changed.

 

Assign and change value of Val for a basic data type

We shall look into an example where we shall assign some data to val and var, and try to change the values they hold.

Kotlin compilation Error – Val cannot be reassigned occurs.

 

Assign and change properties of Val object

We shall look into an example where we shall declare an object to val and try changing the values of its properties.

We have used Data Class in Kotlin to realize properties of an object. The properties of a val object could be changed.

 

Conclusion :

In this Kotlin Tutorial, we have learnt about Val vs Var in Kotlin that var could be changed at any level. Whereas val once assigned, could not be changed, but its properties could be changed.