Kotlin Error: Variable must be initialized
In this tutorial, we shall learn how to handle Kotlin Compilation Error Variable must be initialized. Usually, this compilation error occurs when we try to access a variable (or its methods) which is declared but not initialized.
We shall look into an example where we can reproduce this compilation error.
Reproduce the Error: Variable must be initialized
In the below example, we have declared variable “users” of type ArrayList but not initialized. When we try to add an element to the list, it throws compilation error saying that the variable is not initialized, which is true. We have only declared, but not initialized the variable “users”.
example.kt
import java.util.ArrayList
fun main(args: Array) {
var name: String
name.length
var users: ArrayList
users.add(User("Suresh",25))
users.add(User("Mama",22))
println(users[0])
}
data class User(val name: String = "", val age: Int = 0)
Output
Error:(5, 4) Variable 'name' must be initialized
Error:(5, 9) Expression 'length' of type 'Int' cannot be invoked as a function. The function 'invoke()' is not found
Error:(7, 4) Variable 'users' must be initialized
Fix Kotlin Compilation Error Variable must be initialized
We shall try initializing the two variables “name” and “users” and run the program once again.
example.kt
import java.util.ArrayList
fun main(args: Array) {
var name: String = "NoName"
name.length
var users: ArrayList = ArrayList()
users.add(User("Suresh",25))
users.add(User("Mama",22))
println(users[0])
}
data class User(val name: String = "", val age: Int = 0)
Output
User(name=Suresh, age=25)
Conclusion
In this Kotlin tutorial we have handled “Error Variable must be initialized” by initializing the variable.