0
0
KotlinComparisonBeginner · 3 min read

Val vs Var in Kotlin: Key Differences and Usage Guide

val declares a read-only variable that cannot be reassigned after initialization, while var declares a mutable variable that can be changed. Use val when you want a constant reference and var when you need to update the value.
⚖️

Quick Comparison

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

Factorvalvar
MutabilityImmutable (cannot reassign)Mutable (can reassign)
InitializationMust be initialized onceMust be initialized once
ReassignmentNot allowedAllowed
Use caseFor constants or fixed referencesFor variables that change
Thread safetySafer by defaultLess safe if shared
PerformancePotentially optimized by compilerStandard variable
⚖️

Key Differences

val creates a read-only reference. Once you assign a value to a val variable, you cannot change it later. This makes your code safer because you know the value won't accidentally change. It is similar to a constant but can hold objects whose internal state might still change.

var creates a mutable reference. You can assign a new value to a var variable anytime after initialization. This flexibility is useful when the data needs to change, like counters or user input values.

Choosing between val and var affects code readability and safety. Using val by default encourages immutability, which reduces bugs and makes your program easier to understand.

⚖️

Code Comparison

Here is an example using val to declare a variable that cannot be reassigned.

kotlin
fun main() {
    val name = "Alice"
    println(name)
    // name = "Bob" // This will cause a compile error
}
Output
Alice
↔️

var Equivalent

Here is the same example using var, allowing reassignment.

kotlin
fun main() {
    var name = "Alice"
    println(name)
    name = "Bob"
    println(name)
}
Output
Alice Bob
🎯

When to Use Which

Choose val whenever possible to make your code safer and easier to maintain by preventing accidental changes. Use var only when you need to update the variable's value over time, such as counters, flags, or user inputs. Starting with val and switching to var only when necessary is a good practice.

Key Takeaways

Use val for variables that should not change after assignment.
Use var for variables that need to be reassigned.
val promotes safer, more predictable code.
Start with val and switch to var only if needed.
var offers flexibility but requires careful use to avoid bugs.