In Kotlin if you don\'t want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language r
If you are using Spring container and you want to initialize non-nullable bean field, lateinit
is better suited.
@Autowired
lateinit var myBean: MyBean
lateinit vs lazy
lateinit
i) Use it with mutable variable[var]
lateinit var name: String //Allowed
lateinit val name: String //Not Allowed
ii) Allowed with only non-nullable data types
lateinit var name: String //Allowed
lateinit var name: String? //Not Allowed
iii) It is a promise to compiler that the value will be initialized in future.
NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
lazy
i) Lazy initialization was designed to prevent unnecessary initialization of objects.
ii) Your variable will not be initialized unless you use it.
iii) It is initialized only once. Next time when you use it, you get the value from cache memory.
iv) It is thread safe(It is initializes in the thread where it is used for the first time. Other threads use the same value stored in the cache).
v) The variable can only be val.
vi) The variable can only be non-nullable.