Software Development

Kotlin – val versus var

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.

[wp_ad_camp_1]

Kotlin Codes

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

[wp_ad_camp_2]

“var” variables are modifiable

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

[wp_ad_camp_3]

 

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like