0
0
KotlinComparisonBeginner · 3 min read

Val vs Var in Kotlin: Key Differences and Usage Guide

In Kotlin, val declares a read-only variable whose value cannot be changed after initialization, while var declares a mutable variable that can be reassigned. Use val for constants or values that should not change, and var when you need to update the variable later.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of val and var in Kotlin.

Aspectvalvar
MutabilityImmutable (read-only reference)Mutable (can be reassigned)
Reassignment allowed?NoYes
Initialization requirementMust be initialized onceMust be initialized once
Use caseConstants, fixed valuesVariables that change
Thread safetySafer for concurrencyLess safe if shared
PerformancePotentially optimized by compilerStandard variable
⚖️

Key Differences

The main difference between val and var lies in mutability. A val variable is like a locked box: once you put a value inside, you cannot change it. This makes your code safer and easier to understand because you know the value won't change unexpectedly.

On the other hand, var is like a reusable container that you can open and replace the contents anytime. This flexibility is useful when the value needs to change during program execution, such as counters or user input.

Both val and var must be initialized before use, but only var allows reassignment after initialization. Choosing between them affects code readability, safety, and sometimes performance.

💻

Val Example

kotlin
fun main() {
    val name = "Alice"
    println(name)
    // name = "Bob" // Error: Val cannot be reassigned
}
Output
Alice
↔️

Var Equivalent

kotlin
fun main() {
    var age = 25
    println(age)
    age = 26
    println(age)
}
Output
25 26
🎯

When to Use Which

Choose val when you want to create a variable that should not change after it is set. This helps prevent bugs and makes your code easier to follow. Use var only when you need to update the variable's value later, such as in loops, counters, or when tracking state changes.

As a best practice, prefer val by default and switch to var only when necessary. This approach leads to safer and more predictable code.

Key Takeaways

Use val for variables that should not change after initialization.
Use var for variables that need to be reassigned or updated.
val improves code safety and readability by preventing accidental changes.
Always initialize val and var before use.
Prefer val by default and use var only when mutability is required.