Skip to content
AgileLogics
5 min read

Variables: val and var

Prerequisites: Printing output

A variable gives a name to a value so you can use it later.

Real-world analogy: a variable is a labeled box. A val is a sealed box — once filled, its contents stay. A var is a box you can open and refill.

Syntax

val name = "Ada"   // read-only: can't be reassigned
var score = 0      // mutable: can be reassigned

Example

fun main() {
    val city = "Lagos"
    var temperature = 24

    println(city)
    println(temperature)

    temperature = 27
    println(temperature)

    temperature += 1
    println(temperature)
}

Expected output

Lagos
24
27
28

temperature += 1 is short for temperature = temperature + 1. Kotlin also has temperature++.

Prefer val

Use val by default and var only when the value really needs to change. Code with fewer changing values is easier to understand, and IntelliJ suggests switching a var that's never reassigned to val.

Constants

For fixed values known when the program is compiled, use const val at the top level of a file (outside any function), named in SCREAMING_SNAKE_CASE:

const val MAX_PLAYERS = 4

fun main() {
    println("Up to $MAX_PLAYERS players")
}
Up to 4 players

Common mistakes

  • Reassigning a val:
fun main() {
    val limit = 10
    limit = 20
}
error: 'val' cannot be reassigned.
  • Using a variable before giving it a value: Variable 'total' must be initialized.

Practice

Create a val appName and a var launchCount starting at 0. Increase launchCount twice, then print Notes has launched 2 times.

Hint: put a variable inside a string with $: "$appName has launched ...".

Show solution
fun main() {
    val appName = "Notes"
    var launchCount = 0
    launchCount++
    launchCount++
    println("$appName has launched $launchCount times")
}
Notes has launched 2 times