Question #373EasyNative Android

Explain the difference between val and var in Kotlin?

#kotlin#variables#val-var

Answer

Overview

text
val
and
text
var
define variable mutability in Kotlin.


Key Differences

Feature
text
val
text
var
MutabilityImmutable (read-only)Mutable
Reassignment❌ Cannot reassign✅ Can reassign
Java Equivalent
text
final
Regular variable
Best PracticePrefer
text
val
Use when needed

Examples

val (Immutable)

kotlin
val name = "Alice"
name = "Bob" // ❌ Compile error

val age = 25
age = 26 // ❌ Compile error

var (Mutable)

kotlin
var 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

kotlin
class 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

text
val
unless you need to reassign. Immutability reduces bugs.