VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/difference-between-var-and-val-in-kotlin/

⇱ Difference between var and val in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Difference between var and val in Kotlin

Last Updated : 3 Jun, 2020
var and val are both used to declare variables in Kotlin language. However, there are some key differences between them:

VAR(Variable)

It is a general variable. The value of a variable that is declared using var can be changed anytime throughout the program. var is also called mutable and non-final variable, as there value can be changed anytime. Example:
Output :
Previous marks is 10
New marks 30

VAL(Value)

The object stored using val cannot be changed, it cannot be reassigned, it is just like the final keyword in java. val is immutable. Once assigned the val becomes read-only, however, the properties of a val object could be changed, but the object itself is read-only. Example 1:
Output:
Val cannot be reassigned
Example 2:
output:
Book(name=Java, price=1000)
Book(name=Kotlin, price=1000)
Comment
Article Tags:
Article Tags:

Explore