Kotlin val vs var: Key Differences Explained
Q: What is the difference between val and var in Kotlin?
- Kotlin
- Junior level question
Explore all the latest Kotlin interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Kotlin interview for FREE!
In Kotlin, val and var are used to declare variables, but they have different characteristics:
val (Value):
- Declares an immutable variable, meaning its value cannot be changed once it is assigned.
- Equivalent to a final variable in Java or a constant.
- Must be initialized at the point of declaration or in the constructor if it's a property.
- Provides read-only access to the assigned value.
var (Variable):
- Declares a mutable variable, allowing its value to be reassigned.
- Similar to regular variables in most programming languages.
- Must be initialized at the point of declaration or later in the code.
- Provides both read and write access to the assigned value.
In summary, val is used for immutable values that cannot be changed after initialization, while var is used for mutable variables that can be reassigned. It's generally recommended to use val whenever possible to promote immutability and avoid accidental modifications. Use var when you need the flexibility to modify the value of a variable.


