Any programming language a variable is referred to a location in memory(storage area) to stored data. The type of variable defines the range of value that the variable can hold. So indicate a storage space, each variable should be given a unique identifier.
Basically, val and var both are used to declare a variable. var is like a general variable and can be assigned multiple times and is known as the mutable variable in Kotlin. Whereas val is a constant variable and can not be assigned multiple times and can be Initialized only single time and is known as the immutable variable in Kotlin.
Declaring a variable in Kotlin
Var
is short for variable – The object stored in the variable could change (vary) in time.
private val adapter: HomeAdapter? = null
After the Initialized It will not throw me an error because var is a mutable and it can be assigned multiple times.
Val
is short for 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.
private var adapter: HomeAdapter? = null
After the Initialized It will throw me an error like “Val can not be reassigned”
So to conclude we have learnt about Val vs Var in Kotlin that var could be changed at any level. Whereas val once assigned, could not be changed, but its properties could be changed.