← Back to Kotlin Course | Chapter 2: Variables & Types | Lesson 1 of 7

val vs var

val makes a labeled box you can only fill once, while var makes a labeled box you can refill as many times as you want.

Declaring with val

val creates a reference that can be assigned a value exactly once. Attempting to assign a new value to a val after that is a compile-time error, which helps prevent accidental changes.

Note: Prefer val everywhere possible; it makes code easier to reason about.

Example: Declaring with val

markup
fun main() {
    val name = "Kotlin"
    println("Language: $name")
}

Declaring with var

var creates a mutable reference whose value can be changed later using =. It is used when a value genuinely needs to change over the program's lifetime, such as a running counter.

Example: Declaring with var

markup
fun main() {
    var counter = 0
    counter = counter + 1
    counter += 1
    println("Counter is now $counter")
}

val Reference vs Mutable Contents

A val only locks the reference itself, not necessarily what it points to. A val holding a mutable list still lets you add or remove items -- you just cannot point that val at a different list afterward.

Note: If you need the contents to be unchangeable too, use an immutable collection type.

Example: val Reference vs Mutable Contents

markup
fun main() {
    val items = mutableListOf("apple", "banana")
    items.add("cherry")
    println(items)
}

Choosing val Over var

Idiomatic Kotlin favors val by default and reaches for var only when a variable must be reassigned. This habit reduces bugs caused by unexpected mutation and makes code easier to follow.

Example: Choosing val Over var

markup
fun main() {
    val pi = 3.14159
    var radius = 2.0
    radius = 3.0
    println("Area: ${pi * radius * radius}")
}
Common Mistakes
  1. Trying to reassign a val and being surprised by a compiler error; val means read-only, not just a stylistic default.
  2. Overusing var out of habit from other languages, when most values in Kotlin never actually need to change.
  3. Thinking val makes an object itself immutable; it only prevents reassigning the variable, the object's own contents can still change.
Chapter Summary
  • val declares a read-only reference; it can be assigned once and never reassigned.
  • var declares a mutable reference that can be reassigned as many times as needed.
  • Preferring val by default is idiomatic Kotlin; use var only when reassignment is truly needed.
  • val does not make the referenced object immutable -- a val list can still have items added to it.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.