-
Notifications
You must be signed in to change notification settings - Fork 22
Using val and var in Kotlin
Devrath edited this page Feb 10, 2024
·
1 revision
In Kotlin, val
and var
are keywords used to declare variables, but they have different characteristics in terms of mutability.
-
val (Immutable Variable):
-
val
is short for "value." - Variables declared with
val
are immutable, meaning their values cannot be changed once they are assigned. - They are similar to final variables in Java or constants in other languages.
Example:
val pi = 3.14 // pi cannot be reassigned to a different value
-
-
var (Mutable Variable):
-
var
is short for "variable." - Variables declared with
var
are mutable, meaning their values can be reassigned.
Example:
var count = 10 count = 20 // valid, as count is mutable
-
In general, it's a good practice to use val
whenever possible, as immutability helps make the code more predictable and easier to reason about. Use var
when you need to change the value of the variable during its scope.
Here's a simple guideline:
- Use
val
by default. - Use
var
only if you need to change the value during the execution of the program.
Immutable variables (val
) contribute to more predictable and safer code, as they prevent accidental reassignments and side effects.