Singleton with parameter in Kotlin

后端 未结 11 1146
无人及你
无人及你 2020-11-30 21:51

I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters

11条回答
  •  鱼传尺愫
    2020-11-30 22:21

    solution with lazy

    class LateInitLazy(private var initializer: (() -> T)? = null) {
    
        val lazy = lazy { checkNotNull(initializer) { "lazy not initialized" }() }
    
        fun initOnce(factory: () -> T) {
            initializer = factory
            lazy.value
            initializer = null
        }
    }
    
    val myProxy = LateInitLazy()
    val myValue by myProxy.lazy
    
    println(myValue) // error: java.lang.IllegalStateException: lazy not inited
    
    myProxy.initOnce { "Hello World" }
    println(myValue) // OK: output Hello World
    
    myProxy.initOnce { "Never changed" } // no effect
    println(myValue) // OK: output Hello World
    

提交回复
热议问题