#Lesson 51 : What’s the difference between lazy and lateinit?

#Lesson 51 : What’s the difference between lazy and lateinit?

Both are used to delay the property initialisations in Kotlin

lateinit is a modifier used with var and is used to set the value to the var at a later point.

lazy is a method or rather say lambda expression. It’s set on a val only. The val would be created at runtime when it’s required.

*** lazy ***

val x: Int by lazy { 10 }

*** lateinit ***

lateinit var y: String


António Basti?o

Senior Software Developer | Precision in Coding

4 年

When using val x by lazy returns an instance of delegate. And when the lambda is execute the first time it remembers the value by assigning it to the getter. Imagine that you have a lambda assigned to a lateinit var, is the exactly explanation you gave for the late init var. The initialization is delayed.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了