val, var and const val

Kotlin language Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What happens when you compile this?

fun main() {
    val items = mutableListOf("a")
    items.add("b")
    items = mutableListOf("c")
    println(items)
}
Options
Hint 1 of 1

What exactly is read-only about a val?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A It doesn't compile: a val can't be reassigned

Correct. add() is fine because the list is mutable, but the reference can't change.

Why not the others?
  • B It prints [c]. The reassignment on line 4 isn't allowed.
  • C It prints [a, b]. The code never runs; it fails to compile.
  • D It fails on add(): a val list can't change. The list is a MutableList, so add() is allowed.

30-second answer

var can be reassigned. val can't be reassigned after initialisation, but the object it points to can still change, like a MutableList. const val is a compile-time constant: a primitive or String at top level or in an object, inlined into every use. Prefer val, and immutable types, unless you really need to reassign.

Practise saying it · 30 s. No recording, just a timer

Explain val, var and const val.

Say your answer out loud, then check which of these points you covered:

  • var can be reassigned
  • val is a read-only reference
  • const val is a compile-time constant
  • Prefer val and immutable types

Deep dive

A val with a custom getter can return a different value each time, so 'val' means read-only, not constant.

const values are inlined, so changing one in a library requires recompiling users.

Use const val for keys and tags; it avoids a getter call.

Immutable data (val plus read-only types) is what makes StateFlow and Compose equality work.

Common mistakes

  • Saying a val's contents can't change.
  • Using const for values computed at runtime.
  • Using var for everything 'just in case'.

Senior take & follow-ups

The 'read-only reference vs immutable object' distinction is the point.

Follow-up questions

Think of your answer first, then open the hint.

  1. Can a val change value?

    Show hint

    Its getter can compute a new value, and a mutable object it holds can change.

  2. Where can const val be declared?

    Show hint

    Top level, in an object or a companion object.

Suggest a fix if something here is wrong or out of date.