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.
1 2 3 | // In Kotlin var name = "Turreta" var name = "www.turreta.com" |
[wp_ad_camp_3]