[by lazy] Lazy Initialization of Kotlin



If a property use huge resources when it’s initialized or doesn’t need to be initialized everytime, you could apply Lazy Initialization pattern.
For example, Pizza class provide its dough. But it takes quite long time to make new dough. So let’s get dough only once when use it for the first time.

class Pizza() {
    private var _dough: Dough? = null   //Backing property of dough. It saves data.
    val dough: Dough
        get() {
            if(_dough == null) {
                _dough = getDough()    //get dough only when initial approach
            }
            return _dough!!    //if it has saved data, return the data.
        }
}

Yes. You don’t need to write this whole code in Kotlin. Kotlin suggest lazy.

class Pizza() {
    val dough by lazy { getDough() }
}

lazy internally delay initialization like above code. Moreover unlike the code above, it’s thread-safety.





If there’s a mistake, always welcome your opinion!




android

Back to Top ↑

kotlin

Back to Top ↑

progressBar

Back to Top ↑

compose

Back to Top ↑

editText

Back to Top ↑