Kotlin lazy, lateinit and Delegates

Mohit Sharma
2 min readMay 23, 2017

--

In Kotlin when we define variable either we have to initialize with some value or define them in such way value can be null for those variables. In some cases, we want to initialize the value later but don’t want the variables to have the null value. For example: Suppose you want some variable which should be available at the class level and but will be initialized in the onCreate method. Kotlin provides following the following to implement something similar and based on need we can use one of them

(1) Lazy: It’s same as lazy initialization. Your variable will not be initialized unless you use that variable in your code. It will be initialized only once after that we always use the same value.

val test: String by lazy {
val testString = "some value"
testString
}
fun doSomething() {
println("Length of string is "+test.length)
}

(2) lateinit: it means you will be initializing the value for this variable before accessing it. In case we try to access the variable before initializing it we will see this error “Caused by: kotlin.UninitializedPropertyAccessException: lateinit property test has not been initialized”. You cannot use lateinit for primitive type properties like Int, Long etc. For those, we can use delegates which will be explained in next section

lateinit var test: String
fun doSomething() {
test = "Some value"
println("Length of string is "+test.length)
test = "change value"
}

(3) Delegates.notNull<Any>: It works with primitive type properties also. notNull create an extra object for each property although it’s pretty small and but if you have too many properties it can impact the performance of your app. lateinit is cheaper that Delegates.notNull. So try to use lateinit as compared to Delegates.notNull.

var test by Delegates.notNull<String>()
fun doSomething() {
test = "Some value"
println("Length of string is "+test.length)
test = "change value"
}

--

--