Val vs Var in Kotlin
Kotlin Tutorial – Val vs Var in Kotlin – We shall learn the difference between the usage of keywords val and var in Kotlin Programming Language with Example Kotlin programs.
var hours = 20
val hoursInDay = 24
Let us first look into the actual names of these keywords and then we shall see how Kotlin Programming Language allows us to use these two keywords with examples.
Var – Variable – The object stored in the variable could change (vary) in time.
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. The properties of the object (as Val) could be changed, but the object itself is read-only.\
Assign and change value of Var for a basic data type
We shall look into an example where we shall assign some data to val and var, and try to change the values they hold.
Kotlin Program – example.kt
fun main(args: Array<String>) {
var numberOfHoursPassed = 3
print("Number Of Hours Passed for the day : "+numberOfHoursPassed)
// after ten hours
numberOfHoursPassed = 13
print("\nNumber Of Hours Passed for the day : "+numberOfHoursPassed)
}
Output
Number Of Hours Passed for the day : 3
Number Of Hours Passed for the day : 13
The value of a var could be changed.
Assign and change value of Val for a basic data type
We shall look into an example where we shall assign some data to val and var, and try to change the values they hold.
Kotlin Program – example.kt
fun main(args: Array<String>) {
val numberOfHoursInDay = 24
print("Number Of Hours Passed for the day : "+numberOfHoursInDay)
// after an hour
numberOfHoursInDay = 25
print("\nNumber Of Hours Passed for the day : "+numberOfHoursInDay)
}
Output
Error:(5, 5) Kotlin: Val cannot be reassigned
Kotlin compilation Error – Val cannot be reassigned occurs.
Assign and change properties of Val object
We shall look into an example where we shall declare an object to val and try changing the values of its properties.
Kotlin Program – example.kt
fun main(args: Array<String>) {
val book = Book("The Last Sun",250)
print(book)
book.name = "Incredible Hulk"
print("\n"+book)
}
data class Book(var name: String = "", var price: Int = 0)
Output
Book(name=The Last Sun, price=250)
Book(name=Incredible Hulk, price=250)
We have used Data Class in Kotlin to realize properties of an object. The properties of a val object could be changed.
Conclusion
In this Kotlin Tutorial, 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.