Constants & Variables

Naming your data

A program is mostly data with names attached. In Kotlin you attach a name to a value with one of two keywords:

  • val declares a value β€” a name whose reference is set once and can never be reassigned.
  • var declares a variable β€” a name whose value you can replace later.

Kotlin strongly prefers val. A name that can't be reassigned is a name that can't drift out from under you by accident β€” a whole category of bugs, gone. Android Studio even warns you when you write var for something you never reassign.

Rule of thumb: start with val. Switch to var only when the compiler β€” the program that turns your Kotlin into a runnable app β€” tells you the value actually needs to change.