Sobes.tech
Junior — Middle

What is the difference between declaring variables with 'var' and 'val' in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, var and val are used to declare variables, but they have a fundamental difference:

  • var declares a mutable variable. The value of such a variable can be changed after initialization.
  • val declares an immutable variable, similar to a constant. Its value cannot be changed after assignment.

Example:

var mutableVar = 10
mutableVar = 20  // allowed

val immutableVal = 30
// immutableVal = 40  // compilation error

Using val is recommended when the value should not change, as it increases code safety and readability.