Skip to Content
Course content

4: Variables: val and var

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this one all the time when people are moving from Java or Python to Kotlin. You're writing a piece of logic, everything looks correct, but the IDE is screaming at you with a red underline that simply says Val cannot be reassigned. Let's look at a realistic example of where this happens.

fun main() {
    val currentScore = 0
    println("Welcome to the game! Current score: $currentScore")
    
    // Player hits a target
    currentScore = currentScore + 10 
    println("Nice shot! Your score is now: $currentScore")
}

The "Val cannot be reassigned" Error

If you try to run the code above, it won't even compile. The problem is that I used val to declare currentScore. In Kotlin, val stands for value. Once you assign a value to a val, it's locked in for the rest of its lifetime. It is read-only.

In the example, I'm trying to increment the score, which requires changing the value stored in that variable. But because I told Kotlin this was a val, the compiler is protecting me from accidentally changing something that was meant to stay constant. It's a safety feature, but in this specific case, it's blocking the actual logic of my game.

Switching to Mutable Variables

To fix this, we need to use var. Short for variable, var tells Kotlin that this value is mutable—meaning it can be changed or reassigned later in the program.

fun main() {
    var currentScore = 0
    println("Welcome to the game! Current score: $currentScore")
    
    currentScore = currentScore + 10 
    println("Nice shot! Your score is now: $currentScore")
}

Now the code compiles and runs perfectly. By changing that one keyword, we've told the compiler, "I intend for this value to change, so please let me reassign it."

The Golden Rule of Immutability

You might be wondering, "Why not just use var for everything and avoid the errors?" I'll be honest: you could, but you shouldn't. As a software engineer, I spend a huge chunk of my time debugging state changes. When a variable changes unexpectedly in a large project, it's a nightmare to track down.

My advice is to default to val. Every single time you create a variable, start with val. Only switch it to var if you realize you actually need to change the value later. This makes your code much easier to reason about because you can look at a val and know with 100% certainty that it will never change, no matter how many functions it gets passed into.

  • val: Immutable (Read-only). Use for constants, configuration, or data that doesn't change.
  • var: Mutable (Read-write). Use for counters, accumulators, or state that evolves.



📋 Practical Task

Exercise: Fixing the Temperature Tracker

You are building a simple weather tracking script. However, the current code is broken because it uses val where it should use var, and it uses var for a value that should never change (the city name).

Your Task: Modify the code below so that it compiles and follows the "Golden Rule of Immutability" (use val for things that don't change and var for things that do).

fun main() {
    var city = "New York"
    val temperature = 72
    
    println("Checking weather in $city...")
    
    // The temperature drops
    temperature = 68 
    
    println("The current temperature in $city is $temperature degrees.")
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.