Explain it simply
Variables, simply
A variable is a labelled box. You put a value in the box and fetch it back by name. Kotlin has two kinds of box. A `val` box is sealed as soon as the value goes in, so it can never be swapped for another value. A `var` box can be reopened and given a different value.
Kotlin nudges you toward sealed boxes, because the less that can change, the easier it is to follow what happened. Start with `val` and switch to `var` only when a value truly has to change.
Problem → Why → Solution
The problem: a value that changes behind your back
In the program below every variable is declared with `var`. A discount is subtracted from the price to get the total. Later, someone reuses the name `discount` for a different purpose, but the last line still reads that variable, so it says 'You saved 500' when only 100 was actually taken off.
The compiler reports nothing because, as far as it can tell, the code is valid. Bugs like this are hard to catch precisely because nothing crashes; the program quietly prints a wrong answer.
fun main() {
var price = 1000
var discount = 100
val total = price - discount
discount = 500 // the name is reused for something else
println("Total: $total")
println("You saved $discount") // prints 500, but only 100 was applied
}How val prevents this bug
If `discount` is declared with `val`, the line `discount = 500` fails right there with the compile error `error: 'val' cannot be reassigned.` A quiet logic bug becomes a visible error while you are still typing. That is why `val` is the default choice.
Core concept: val, var and types
`val name = value` declares a read-only variable. Its value is set once, usually at the declaration, and can never be assigned again. `var name = value` declares a changeable variable that you may reassign with `name = anotherValue`. With both kinds, the type is fixed once and for all.
You do not have to write the type; Kotlin infers it from the initial value (type inference). `val count = 10` is an `Int`, `val price = 9.99` is a `Double` and `val name = "Aye"` is a `String`. You may still write it out as `val count: Int = 10`. If you declare a variable without an initial value, there is nothing to infer from, so you must write the type.
A fixed type holds for `var` too. After `var n = 10`, the variable `n` is an Int, and `n = 3.5` fails with `error: assignment type mismatch: actual type is 'Double', but 'Int' was expected.` So does `n = "ten"`. This is where Kotlin differs from languages such as Python and JavaScript: a variable's value may change, but its type may not.
The most important subtlety is that `val` locks the name, not the contents of the object the name points to. With `val scores = mutableListOf(70, 85)` you cannot swap in another list with `scores = mutableListOf()`, but `scores.add(90)` still adds to the list. The table below shows what can change in each case.
| Declaration | Reassign the name? | Change the contents? |
|---|---|---|
| val list = mutableListOf(1) | No | Yes (add, remove) |
| var list = mutableListOf(1) | Yes | Yes |
| val list = listOf(1) | No | No (read-only type) |
One last point: a `val` does not have to get its value at the declaration. You can write `val label: String` and assign exactly once later, for example once in each branch. Using it before it is assigned gives `error: variable 'x' must be initialized.`, and assigning twice gives `'val' cannot be reassigned.` The compiler checks every path.
- Declare with val or var
- The first value fixes the type
- val: one assignment, then sealed
- var: reassign, same type only
val locks the name, not the object it points to. The contents of a mutable list can still change.
General pattern: declaring variables
val readOnlyName = initialValue
var changeableName = initialValue
changeableName = anotherValueOfTheSameType
val explicitType: Type = value
val assignedLater: Type
assignedLater = valueAfter `val` or `var` come the name, then an optional `: Type`, then `= value`. Only a `var` can be given a new value with a later `=`. A `val` without an initial value may be assigned once later, and then the type must be written.
A player score tracker
This program tracks one player's score. Notice that only the score, which really changes, is a `var`, and everything else is a `val`. The `if` / `else` gets its own lesson next; for now read it as 'first block when the condition is true, second block otherwise'.
fun main() {
val playerName = "Aye"
var score = 0
val bonus = 15
score += 10
score += bonus
println("$playerName scored $score")
val history = mutableListOf(score)
history.add(40)
println("History: $history")
val rating: String
if (score >= 25) {
rating = "good"
} else {
rating = "keep going"
}
println("Rating: $rating")
}Code breakdown
- A read-only value
val playerName = "Aye"The player's name never changes in this game, so it is a `val`. Kotlin infers the type `String`. Writing `playerName = "Ko"` further down would be a compile error.
- A changeable value
var score = 0The score grows during play, so it is a `var`. From `0` Kotlin infers `Int`, so later `score = "high"` is not allowed.
- Updating with +=
score += 10`score += 10` is shorthand for `score = score + 10`. It is allowed because `score` is a `var`. Because `bonus` is a `val`, writing `bonus += 5` would be a compile error. After the second `+=` the score is 25.
- val with a mutable object
val history = mutableListOf(score)`val history` locks the name, but `mutableListOf` creates a list that can change. So the next line, `history.add(40)`, may add to it and gives `History: [25, 40]`. Swapping in a different list with `history = mutableListOf()` would not be allowed.
- Assigning a val later
val rating: StringThis `val` has no initial value, so the type `String` must be written. Both the `if` and the `else` path assign `rating` exactly once, so the compiler accepts it. If one path forgot to assign it, `println(rating)` would be a compile error.
Aye scored 25
History: [25, 40]
Rating: good- Always start with val
- Compile and see if a reassignment is needed
- Ask whether it truly must change
- Switch to var only then
No reassignment needed
Keep val: the compiler guarantees the name never changes
A reassignment is needed
Change that one declaration to var and keep the rest as val
const val and naming conventions
For a value that is the same across the whole program, such as a maximum player count or a tax rate, use `const val`. `const` means the value is known at compile time, so it is limited to simple types such as numbers, Booleans and Strings, and it can be declared at the top level (or in an object) but not inside a function: writing `const val MAX = 5` in a function gives `modifier 'const' is not applicable to 'local variable'.`
const val MAX_SCORE = 100
fun main() {
val playerScore = 85
val percent = playerScore * 100 / MAX_SCORE
println("Score: $playerScore of $MAX_SCORE ($percent%)")
}For names, ordinary variables use camelCase (`playerScore`, `totalPrice`). `const val` names use uppercase with underscores (`MAX_SCORE`), so a fixed value is recognizable at a glance in code. A name should say what the variable stands for: `playerScore` beats `x`.
Reading the compiler messages from this lesson
| Message | Cause | Fix |
|---|---|---|
| 'val' cannot be reassigned. | A val is assigned a second time | Change it to var if it must change, otherwise delete the line |
| assignment type mismatch: actual type is 'String', but 'Int' was expected. | A value of a different type is put into a var | Use a value of the same type, or declare a new variable |
| variable 'x' must be initialized. | It is read before being assigned | Assign it on every path before reading |
| conflicting declarations: | The same name is declared twice in one scope | Rename one of them |
| unresolved reference 'add'. | A read-only list from listOf has no add | Use mutableListOf when the list must change |
In real projects
val and var in real Kotlin code
In Kotlin codebases `val` is the default. IntelliJ IDEA flags a `var` that is never reassigned and suggests declaring it as `val`, and in code review a `var` invites the question of why it has to change. Most properties of data classes are `val`, so an object does not change after it is created, which keeps the code easy to read.
`var` has its place: counters, accumulators inside loops, and holders of changing UI state. When a program runs on several threads, a reference that cannot change cannot be swapped by another thread by accident, which is safer; but if the object the name points to is itself mutable, it needs separate care. That is why shared collections are often exposed through read-only types such as `listOf`.
Common mistakes
Common mistakes
1. Declaring everything as var just in case
Using `var` everywhere switches off the compiler's protection: any line may change any value, and bugs like the discount example above come back. Start with `val`, and switch to `var` only when the compiler says `'val' cannot be reassigned`.
2. Assuming val makes the object unchangeable
`val items = mutableListOf("tea")` can still be changed with `items.add("coffee")`, because `val` only locks the name `items`. If you really want a list that cannot change, use `listOf(...)`; then `items.add(...)` itself fails with `unresolved reference 'add'.`
3. Expecting a var to change its type
After `var version = 1`, writing `version = "two"` gives `error: assignment type mismatch: actual type is 'String', but 'Int' was expected.` To store another type, declare a new variable. You could pick a very wide type such as `var version: Any = 1`, but that throws away most of the type checking, so avoid it.
4. Reading a val before it is assigned
Writing `println(label)` right after `val label: String` gives `error: variable 'label' must be initialized.` Assigning on only one branch of an `if` is not enough either; assign on every path first, then read.
Best practices
Best practices
- Start every declaration as `val` and change it to `var` only when you must reassign.
- Declare a variable close to where it is first used instead of collecting them all at the top of a function.
- When you hand a mutable collection to other code, expose it as a read-only type such as `List`.
- Let names carry meaning: `lessonCount` rather than `n`, and `MAX_SCORE` for a fixed value.
Mini challenge
Mini challenge: a savings tracker
Write a tracker for a savings goal. Only the balance, which changes, should be a `var`; everything else is a `val`.
- Declare `owner` and `goal` (50_000) as `val` and `balance` (0) as `var`
- Add two deposits (12_000 and 20_000) with `balance += ...`
- Work out how much of the goal remains with a `val remaining`
- Declare `val status: String` without a value, assign it once in each of the `if` and `else` paths, and print everything
fun main() {
// TODO: val owner, val goal = 50_000, var balance = 0
// TODO: two deposits with += (12_000 and 20_000)
// TODO: val remaining = goal minus balance
// TODO: val status: String, assigned in both branches of an if / else
// TODO: one println with owner, balance, goal, remaining and status
}Expected: Mya has 32000 of 50000 (18000 to go): keep saving
Show hint
Underscores in `50_000` only make the number easier to read; the value is 50000. Assign `status` with `if (balance >= goal) { status = ... } else { status = ... }`. Also try reassigning a `val` once, so you have seen the compiler error yourself.
Show solution
fun main() {
val owner = "Mya"
val goal = 50_000
var balance = 0
balance += 12_000
balance += 20_000
val remaining = goal - balance
val status: String
if (balance >= goal) {
status = "goal reached"
} else {
status = "keep saving"
}
println("$owner has $balance of $goal ($remaining to go): $status")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- `val` is a name that cannot be reassigned and `var` one that can; start with `val`.
- The type is inferred from the initial value and then fixed, even for a `var`.
- `val` locks only the name; the contents of an object such as a mutable list can still change.
- Assign a `val` without an initializer once on every path before reading it, and write fixed values as `const val`.
Kotlin language guide — Kotlin