Difference Between Val and Var

Let’s learn about the actual difference between val and var.

Val and var are essentially both used to declare a variable. Var is a general variable and can be allocated several times, and is regarded in Kotlin as a mutable variable. Whereas val is a constant variable which can not be allocated multiple times and is known as the immutable variable in Kotlin, which can be initialised only once.

{codeString1}

1
2
val price = 1
    price = 2

I declared a variable with a val keyword and initialized it. If i try to reinitialise it again the compiler throws me error “Val can not be reassigned”

{codeString2}

1
2
var quantity = 2
    quantity = 5

I declared a variable with a var keyword and initialized it. If I try to reinitialise it again this time compiler wont throw me any error. I can mutate this variable any number of times as per the requirement.