Kotlin lateinit
Kotlin lateinit – To declare non null Kotlin Variables without initialization, use lateinit keyword during declaration of the variable. Initialization of that variable could be done at a later point in code.
Note : lateinit is supported from Kotlin 1.2. Make sure you are updated to latest Kotlin.
Example 1 – Kotlin lateinit
In the following example, we will late initialize variable person1
.
Kotlin Program – example.kt
</>
Copy
/**
* Example to demonstrate lateinit keyword
*/
// variable that we shall initialize at a later point in code
lateinit var person1:Person
fun main(args: Array<String>) {
// initializing variable lately
person1 = Person("Ted",28)
print(person1.name + " is " + person1.age.toString())
}
data class Person(var name:String, var age:Int);
Output
Ted is 28
Conclusion
In this Kotlin Tutorial, we have learnt to declare a non null Kotlin Variable without initialization using lateinit keyword with the help of Example Kotlin programs.