Var and Val both both are used for store a value of data. They are different in a mechanism , where Var can change the value but Val is constant. Let’s check compare in detail and examples.
Var
– Variable
– The object stored in the variable could change (vary) in time. Means you can change or assign new value in variable latter.
var reasignableString = "hello" reasignableString = "Hello eyehunt" // OK
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 (Final variables etc). The properties of the object (as Val) could be changed, but the object itself is read-only.
val constant = "hello" constant = "Var vs Val" // Not allowed for `val`
val
in kotlin
is like final
keyword in java
Other ways to says same :
Variables defined with var
are mutable (Read and Write)
Variables defined with val
are immutable (Read only)
Read more Kotlin tutorials