Skip to the workspace
Pebellslearn by building
Variables and Data Types  ›  Lesson

val vs var

val vs var 12 minA val is a read-only reference that is assigned once, while a var can be reassigned; prefer val and switch to var only when the value truly has to change.

kotlin / val vs var

Explore each scene at your own pace.

01 · The rule

The rule

val vs var

A val is a read-only reference that is assigned once, while a var can be reassigned; prefer val and switch to var only when the value truly has to change.

Compare rebinding a variable with changing the object a val refers to.

At the café, the shop's name never changes, but the count of cups sold goes up with every order. When you store these in a program, telling Kotlin which is which prevents a whole family of bugs where something changes that never should.

The rule

val is fixed once; var may be reassigned. Start with val.

val shopName = "Pebble Café"
var cupsSold = 0

cupsSold = cupsSold + 1    // fine: var can be reassigned
cupsSold += 2              // also fine, now 3
shopName = "Other Café"    // compile error: val cannot be reassigned
  • val (value) is assigned exactly once. After that, the name always refers to the same thing. It is like final in Java.
  • var (variable) can be given a new value as often as you like, as long as it has the same type. cupsSold = "three" is an error because cupsSold is an Int.

A val can be declared first and assigned later, but only once:

val openingHour: Int
openingHour = 8            // first and only assignment

Read-only is about the name, not the object. A val pointing at a mutable list still lets you change the list:

val orders = mutableListOf("latte")
orders.add("mocha")        // allowed: same list, new contents
orders = mutableListOf()   // error: that would reassign the val

There is also const val for fixed values known when the program is compiled, such as const val MAX_CUPS = 12. It works only at the top level or inside an object, and only for primitive types like Int and for String.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.