CodeBlanks Logo Icon CodeBlanks

val and var

Learn to declare variables with val (immutable) and var (mutable).

val and var

In Kotlin you declare two kinds of variables. A variable declared with val (value) is assigned once and cannot be changed afterwards; this is called immutable. A variable declared with var (variable) can be reassigned later; this is called mutable.

Kotlin recommends using val by default and switching to var only when the value really needs to change.

val pi = 3.14    // immutable
var counter = 0   // mutable
counter = counter + 1

Practice Declare a counter

Write a fun main(). Declare var counter = 0. Then increment with counter = counter + 1 and print with println(counter).

Sample solution

Main.kt
fun main() {
    var counter = 0
    counter = counter + 1
    println(counter)
}

Expected output

1

When to use val?

The Kotlin community recommends using val by default. Variables declared with val are safer; since they don't change after assignment, code behavior is more predictable.

You switch to var only for loop counters, fresh user input, or running totals. This habit is especially valuable in concurrent code.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which cannot be reassigned?

  • const
  • var
  • val Correct answer
  • lateinit

Explanation: A variable declared with val is assigned once.

2 val and var: fill in the missing part

Question
____ counter = 0
counter = counter + 1
Answer
var counter = 0
counter = counter + 1

Explanation: A var variable can be changed later.

3 Which statement is true?

  • val is mutable, var is immutable
  • val is immutable, var is mutable Correct answer
  • Both are immutable
  • Both are mutable

Explanation: val is immutable, var is mutable.

All lessons in Beginner