Avatar ·

What is the difference between var and val in Kotlin? When to use which?

Hello everyone! I just started learning Kotlin after Java and got confused about variable declarations. Kotlin has two keywords: var and val. I understand that both are used to create variables, but I can't grasp when to use one or the other.

In Java, I'm used to variables always being mutable unless final is specified. But here it's the opposite — it seems like val is used more often, but I don't understand why.

Here's an example of my code that confuses me:

fun main() {
    var name = "Anna"
    name = "Maria"  // works
    
    val city = "Moscow"
    // city = "Saint Petersburg"  // compilation error!
    
    var count = 0
    count = count + 1  // works
    
    val maxCount = 100
    // maxCount = 200  // compilation error!
}