What is the difference between var and val in Kotlin?

Technology CommunityCategory: KotlinWhat is the difference between var and val in Kotlin?
VietMX Staff asked 4 years ago
  • var is like general variable and it’s known as a mutable variable in kotlin and can be assigned multiple times.
  • val is like Final variable and it’s known as immutable in Kotlin and can be initialized only single time.
+----------------+-----------------------------+---------------------------+
|                |             val             |            var            |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized  | Mutable(can able to change|
|                | can't be reassigned)        | value)                    |
+----------------+-----------------------------+---------------------------+
| Example        | val n = 20                  | var n = 20                |
+----------------+-----------------------------+---------------------------+
| In Java        | final int n = 20;           | int n = 20;               |
+----------------+-----------------------------+---------------------------+