Sunday, 24 December 2017

Kotlin: lateinit : Late initialized properties

By default, kotlin do not allow uninitialized properties. You must initialize them at the time of declaration (or) in the constructor. Let me explain with an example.

HelloWorld.kt
class Employee{
 var id : String
 var name : String
 var city : String
}

When you try to compile above program, you will end up in below error.

         ERROR: Property must be initialized or be abstract (2, 2)
         ERROR: Property must be initialized or be abstract (3, 2)
         ERROR: Property must be initialized or be abstract (4, 2)
        
How to resolve above problem?
There are three ways:
         a. Initialize the variables at the time of declaration
         b. Define the variables in constructor
         c. Use late initialization


Initialize the variables at the time of declaration
class Employee {
 var id: String = "123"
 var name: String = "Krishna"
 var city: String = "Ongole"
}

Define the variables in constructor
class Employee {
 var id: String
 var name: String
 var city: String

 constructor() {
  id = "123"
  name = "Krishna"
  city = "Ongole"
 }
}

Use late initialization
By using lateinit keyword, we can inform kotlin that this variable will be initialized at later point of time.

class Employee {
 lateinit var id: String
 lateinit var name: String
 lateinit var city: String
}

Can I access lateint property before initialization?
No, If you try to access a lateinit property before initialization, you will end up in 'UninitializedPropertyAccessException'

HelloWorld.kt
class Employee {
 lateinit var id: String
 lateinit var name: String
 lateinit var city: String
}

fun main(args: Array<String>) {
 var obj = Employee()

 println("Id : ${obj.id}")
}


When you try to run above program, you will end up in below exception.

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property id has not been initialized
         at Employee.getId(HelloWorld.kt:2)
         at HelloWorldKt.main(HelloWorld.kt:10)

To resolve the error define the lateinit properties before accessing.

HelloWorld.kt

class Employee {
 lateinit var id: String
 lateinit var name: String
 lateinit var city: String
}

fun main(args: Array<String>) {
 var obj = Employee()
 
 obj.id = "123"

 println("Id : ${obj.id}")
}

Output
Id : 123





Previous                                                 Next                                                 Home

No comments:

Post a Comment