0
0
KotlinDebug / FixBeginner · 3 min read

How to Fix 'val cannot be reassigned' Error in Kotlin

In Kotlin, val declares a read-only variable that cannot be changed after assignment. To fix the 'val cannot be reassigned' error, change val to var if you need to modify the variable later, or avoid reassigning it.
🔍

Why This Happens

Kotlin uses val to declare variables that cannot be changed once set. This means you cannot assign a new value to a val variable after its initial assignment. Trying to do so causes the compiler error 'val cannot be reassigned'.

kotlin
fun main() {
    val number = 10
    number = 20  // Error: Val cannot be reassigned
    println(number)
}
Output
error: val cannot be reassigned number = 20 // Error: Val cannot be reassigned ^
🔧

The Fix

To fix this error, use var instead of val if you want the variable to be changeable. var declares a mutable variable that can be reassigned. Alternatively, avoid reassigning a val variable if immutability is intended.

kotlin
fun main() {
    var number = 10
    number = 20  // This is allowed
    println(number)  // Output: 20
}
Output
20
🛡️

Prevention

To avoid this error, decide if a variable should be mutable or immutable before declaring it. Use val for values that should not change, which helps prevent bugs. Use var only when you need to update the variable later. Many Kotlin style guides recommend preferring val for safety and clarity.

Also, use your IDE's linting tools to warn about unnecessary var usage or accidental reassignment attempts.

⚠️

Related Errors

Similar errors include:

  • Uninitialized variable: Declaring a val without assigning a value immediately causes an error unless declared as lateinit var or nullable.
  • Reassignment of a property with a custom getter: Properties with only getters cannot be reassigned.

Fixes usually involve changing val to var or redesigning the code to avoid reassignment.

Key Takeaways

Use val for variables that should not change after assignment.
Change val to var if you need to reassign the variable later.
Plan variable mutability before coding to avoid reassignment errors.
Use IDE linting to catch improper reassignment attempts early.
Understand Kotlin's immutability concept to write safer code.