🤖Kotlin: What are the differences between lateinit and Delegates.notNull ❓

Michael M.H
2 min readSep 27, 2022

--

Hi, this is Michael againđź‘‹! Today I want to discuss about the basic features and the differences of the implementations between both lateinit and Delegates.notNull.

Have you ever thought what the differences are between lateinit and Delegates.notNull? As you might know, both lateinit and Delegates.notNull delays the initialization to prevent nulls from entering objects. They seem to have many similarities. You might think that, there may be performance differences due to different internal implementations, but not sure what kind of differences they have.

đź”—Just before we start here are the links related to the topic
đź“Śhttps://kotlinlang.org/docs/properties.html
đź“Śhttps://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/not-null.html

đź‘˝First of all, what is lateinitâť“
To make it simple, it is just a function that helps delay the initialization of properties. Since it is always initialized, it can be handled as non-null. The following are the brief description of the features.

  • Only var properties can be used (Since val is not possible, it is assumed that it will be changed)
  • Primitive types (Int, Long, Boolean, etc) are not allowed
  • Property cannot be null
  • Unable to create custom getter/setter
  • If it get accessed or used before initialization, an UninitializedPropertyAccessException will occur.
lateinit var test1:Testfun main(args: Array<String>) {    // initializing variable lately
test1 = Test("Michael",30)
print(test1.name + " : " + test1.age.toString())
}
data class Test(var name:String, var age:Int)

đź‘˝What is Delegates.notNull()âť“
Delegates.notNull() will cause the object to be created with a non-null type. You can declare it with var but you can’t assign null to the object (You can assign a non-null object instead). You can use this when you want to delay the initialization of mutable and non-null values.

📋Let’s list up the features of Delegates.notNull().

  • primitive type can also be used
  • Exception will be raised if used before initialization
  • You will get a compilation error when trying to set null value
  • Not as performant / efficient as lateinit
var age: Int by Delegates.notNull()// println(age) // IllegalStateException will be raisedage= 30
println(age) // 30

🔎After all, what are the key differences?

  • Delegates.notNull can also use primitive types but not lateinit
  • To use primitive type, use Delegates.notNull
  • You cannot create custom setters or getters with lateinit
  • Delegates.notNull can be difficult to to use with external injection libraries like Dagger

👨‍💻I think that is about it for today! Thank you for reading until the end!

--

--

Michael M.H

🥋 Karate Instructor / 🤖Mobile developer / 👨‍💻 IT Consultant / 🎮 Creator / FX Crypto Trader Bro