Explain the difference between val and var in Kotlin?
#kotlin#variables#val-var
Answer
Overview
text
valtext
varKey Differences
| Feature | text | text |
|---|---|---|
| Mutability | Immutable (read-only) | Mutable |
| Reassignment | ❌ Cannot reassign | ✅ Can reassign |
| Java Equivalent | text | Regular variable |
| Best Practice | Prefer text | Use when needed |
Examples
val (Immutable)
kotlinval name = "Alice" name = "Bob" // ❌ Compile error val age = 25 age = 26 // ❌ Compile error
var (Mutable)
kotlinvar count = 0 count = 1 // ✅ Allowed count++ // ✅ Allowed
Important: Reference vs Content
kotlin// val = immutable reference val list = mutableListOf(1, 2, 3) list.add(4) // ✅ Allowed - modifying content list = mutableListOf() // ❌ Error - reassigning reference // var = mutable reference var numbers = listOf(1, 2, 3) numbers = listOf(4, 5, 6) // ✅ Allowed
In Classes
kotlinclass User { val id: String = "123" // Cannot change var name: String = "Alice" // Can change fun updateName(newName: String) { name = newName // ✅ OK // id = "456" // ❌ Error } }
Best Practices
kotlin// ✅ Prefer val (immutable by default) val name = "Alice" val age = 25 // ✅ Use var only when needed var counter = 0 for (i in 1..10) { counter += i } // ❌ Avoid unnecessary var var constant = "API_KEY" // Should be val
Rule of Thumb: Always use
unless you need to reassign. Immutability reduces bugs.textval