How to Lazy Initialize with a parameter in Kotlin

后端 未结 1 1607
故里飘歌
故里飘歌 2021-02-18 13:00

In Kotlin, I could perform Lazy Initialization without Parameter as below declaration.

val presenter by lazy { initializePresenter() }
abstract fun initializePre         


        
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-18 13:36

    You can use any element within the accessible scope, that is constructor parameters, properties, and functions. You can even use other lazy properties, which can be quite useful sometimes. Here are all three variant in a single piece of code.

    abstract class Class(viewInterface: V) {
      private val anotherViewInterface: V by lazy { createViewInterface() }
    
      val presenter1 by lazy { initializePresenter(viewInterface) }
      val presenter2 by lazy { initializePresenter(anotherViewInterface) }
      val presenter3 by lazy { initializePresenter(createViewInterface()) }
    
      abstract fun initializePresenter(viewInterface: V): T
    
      private fun createViewInterface(): V {
        return /* something */
      }
    }
    

    And any top-level functions and properties can be used as well.

    0 讨论(0)
提交回复
热议问题