Showing posts with label by lazy. Show all posts
Showing posts with label by lazy. Show all posts

Sunday, 17 May 2020

lateinit Vs by lazy


Both "lateinit" and "by lazy" are Kotlin Property initializers.

lateinit:
  • Use it with mutable variable [var]
  • Allowed with only non-nullable data types
  • This modifier is not allowed on properties of primitive types
  • It is a promise to compiler that the value will be initialized in future.
  • If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
by lazy:
  • Lazy initialization was designed to prevent unnecessary initialization of objects.
  • Your variable will not be initialized unless you use it.
  • It is initialized only once. Next time when you use it, you get the value from the memory.
  • It is thread safe (It initializes in the thread where it is used for the first time. Other threads use the same value stored in the cache).
  • The variable can only be val.
  • The variable can only be non-nullable.
class Basic {
    private lateinit var strMsg: String
    private val strMsg1: String by lazy {
        println("Lazy Initializing - Variable born")
        return@lazy "Tester"
    }

    fun initBasic() {
        //Late Initialization - Check
        println("strMsg initialization status is ${::strMsg.isInitialized}");
        strMsg = "Testing"
        println("strMsg value is $strMsg, now the initialization status is ${::strMsg.isInitialized}");

        //Lazy Initialization - Check
        println("strMsg1 value is ${strMsg1}");
    }
}

fun main(ar: Array<String>) {
    Basic().initBasic()
}

Console Output:

strMsg initialization status is false
strMsg value is Testing, now the initialization status is true
Lazy Initializing - Variable born
strMsg1 value is Tester