Skip to content

Difference Between Var and Val in Kotlin

  • by

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.

What is the difference between var and val in Kotlin

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 varare mutable (Read and Write)

Variables defined with valare immutable (Read only)

 

Read more Kotlin tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *