Menu
Coddy logo textTech

Val vs Var

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 5 of 93.

In Kotlin, you use val and var to store values.

var creates a variable. Its value can be changed later:

fun main() {
    var score = 10
    println(score)  // 10
    score = 20
    println(score)  // 20
}

val creates a read-only value. The name cannot be reassigned once initialized. This does not make an object referenced by it deeply immutable:

fun main() {
    val name = "Alice"
    println(name)  // Alice
    // name = "Bob"  // ❌ Error! Val cannot be reassigned
}

When to use which?

  • Use val by default. If a value doesn't need to change, make it read-only.
  • Use var only when you know the value will need to change.
challenge icon

Challenge

Beginner

Create a read-only value called language with the value "Kotlin" and a variable called age with the value 25. Print both values on separate lines.

Try it yourself

fun main() {
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground