SDSnipDojo
← All lessons
Lesson 02 / 126 steps3 exercises

val and var

Read-only and mutable bindings — when each one fits.

1. val — read-only bindings

val declares a binding you assign once. After that, the value cannot be reassigned:

val pi = 3.14159
val name = "Ada"
// pi = 3.0   // compile error

Prefer val by default — it makes code easier to follow because the value can't drift.

2. Use a val

Implement double(n) so it returns n * 2. Inside the function, declare val factor = 2 and use it.

Starter code

fun double(n: Int): Int {
    val factor = 2
    return n
}

3. var — mutable bindings

var declares a binding you can reassign as many times as you need:

var count = 0
count = count + 1     // ok
count = count + 1     // ok again
count++               // shorthand for count = count + 1

Compound operators like +=, -=, ++, -- work on var (they all mutate).

4. Mutate a var

Implement stepUp(start) that takes a number, adds 5 to it, then adds 3 more, and returns the result. Do it by reassigning a single var.

Starter code

fun stepUp(start: Int): Int {
    var n = start
    return n
}

5. val vs var — when to use which

They look similar, but they convey very different intent:

val name = "Ada"      // identity — never changes
var score = 0         // counter — designed to change
Use val when…Use var when…
The value is computed once and usedYou're accumulating, counting, or stepping through state
It represents identity (name, pi)It represents progress (count, total)

Rule of thumb: start with val. Switch to var only when you genuinely need to reassign.

6. Both together

Implement bumpFromBase() using both kinds of declaration:

  • a val base = 10
  • a var n initialised to base
  • increment n twice with n++
  • return n

Expected: 12.

Starter code

fun bumpFromBase(): Int {
    val base = 10
    var n = base
    return n
}

Run this Kotlin lesson in your browser

SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.

Sign in to run this code →