Kotlin Lazy Init

May 15, 2019
Initialize and assign variable only when referred/used
class App {
    val analytics by lazy {
        // assume some heavy initialization
        FirebaseAnalytics.getInstance(App.application)
    }

    fun testAnalytics() {
        // analytics is only initialized once and store in variable for subsequent call
        analytics.logEvent("Hello", null)
        analytics.logEvent("Hello again", null)
    }
}

NOTE: Reference Lazy - By default, the evaluation of lazy properties is synchronized.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.