Skip to content

Using val and var in Kotlin

Devrath edited this page Feb 10, 2024 · 1 revision
Screenshot 2024-02-10 at 2 34 40β€―PM

In Kotlin, val and var are keywords used to declare variables, but they have different characteristics in terms of mutability.

  1. 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
  2. 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.

Clone this wiki locally