Software Development

Kotlin – val versus var

Kotlin key exists Map

What is the difference between the keywords val and var in Kotlin? If you’re coming from Java, val refers to variable that cannot be updated after it has been assigned a value; while var is the usual writable variable whose value can always be changed by other codes.

“val” is like “final” in Java

Consider the following codes from Java and Kotlin.

Java codes

Line 14 causes compilation error as it is not allowed to change the value of a final variable after it has been initialized to some value.


Kotlin Codes

Line 13 causes a compilation error as val variables’ values are unchangeable.


“var” variables are modifiable

var are non-constant variables whose values can be changed anytime.



Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like