Every time you create a name in Kotlin, the language makes you answer one question first: will this value ever change? There are two keywords, one for each answer:
valdeclares a read-only name — it is assigned exactly once and can never be reassigned.vardeclares a variable — the value is allowed to change later.
This is not just style. When you write val, the compiler guarantees the value never changes — if any line of your program tries to reassign it, the program simply refuses to compile. Whole categories of bugs disappear before the code even runs. That is why Kotlin programmers reach for val by default and only use var when a value genuinely needs to change — a counter, a running total, a position that moves:
val pi = 3.14159 // fixed forever — perfect for val
var lives = 3 // will go down when the player is hit
lives -= 1 // OK — lives was declared with var
println(lives) // prints 2
Notice there are no type annotations: Kotlin infers that pi is a Double and lives is an Int from the values you assign. And if you declare something with var and never change it, the IDE nudges you the other way: Variable is never modified, so it can be declared using 'val'.
The trap:
Sooner or later you will try to reassign a val. The compiler stops you with this exact error — read it carefully, because it points at the precise line that tried to do the changing:
error: 'val' cannot be reassigned.
maxLives = 5
^^^^^^^^
The carets underline the exact name that was declared with val, and the two honest ways out are: keep val and stop reassigning, or switch the declaration to var because the value really does need to change. Compound operators hit the same wall — maxLives += 1 fails with the very same 'val' cannot be reassigned. message, because += is just a reassignment in disguise.
Assignment
Follow the Coding Tutorial to build a tiny game setup with one constant and one variable:
- Declare a read-only
maxLivesequal to3— the rules of the game never change — and print it. - Declare a variable
scorestarting at0, add10and then5to it with+=, and print the total.
The exact expected output is:
maxLives = 3
score = 15
Hint
Use println("maxLives = $maxLives")-style string templates: $name drops a value into the middle of a string. And if the compiler says 'val' cannot be reassigned., the name you are changing was declared with val — the one value that must change here is score, so declare it with var.
Free plan: 30 tutor messages. PRO is unlimited.
