Difference between lateinit and lazy in Kotlin

lateinit

  • lateinit is used when you just want to declare a variable but don't want to initialize it. But you make sure that you are going to initialize the variable in future before accessing it while execution. 
 private lateinit var courseName: String
fun fetchCourseName(courseId: String) {
courseName = courseRepository.getCourseName(courseId)
}
  • If you do not initialize your variable before accessing it you will get the exception UninitializedPropertyAccessException.
  • If you want to check if the variable is initialized before accessing it you can use isInitialized property
 if(this::courseName.isInitialized) {
// access courseName
} else {
// some default value
}
  • When you want to use lateinit then you can't use var variables, you can only use var variables.
  • lateinit variables can be declared either inside a class or at the top level property.
  • lateinit are only used for non-primitive variables.
  • lateinit doesn't allow null values.

lazy

  • lazy is used for initializing class objects. If you use lazy keyword to initialize an object, then the object is created only when it is called, otherwise the object will not be created.
 class SomeClass {
private val heavyObject: HeavyClass by lazy {
HeavyClass()
}
}
  • If you use lazy keyword to initialize an object and if you call that object again in your code, then in this case you will call the same object. lazy keyword forbids to allocate different space for the same object.
 class SomeClass {
private val heavyObject: HeavyClass by lazy {
println("Heavy Object initialised")
HeavyClass()
}
fun accessObject() {
println(heavyObject)
}
}

fun main(args: Array<String>) {
val someClass = SomeClass()
println("SomeClass initialised")
someClass.accessObject()
someClass.accessObject()
}
Output
 SomeClass initialised
Heavy Object initialised
HeavyClass@2a84aee7
HeavyClass@2a84aee7

Reference

Comments