2016-03-26 85 views
7

在Kotlin中,我可以執行不帶參數的Lazy Initialization(如下面的聲明)。如何使用Kotlin中的參數進行延遲初始化

val presenter by lazy { initializePresenter() } 
abstract fun initializePresenter(): T 

但是,如果我有一個參數,我initializerPresenter即viewInterface,我怎麼能傳遞參數到懶惰Initiallization?

val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) } 
abstract fun initializePresenter(viewInterface: V): T 

回答

13

您可以使用可訪問範圍內的任何元素,即構造函數參數,屬性和函數。你甚至可以使用其他的懶惰屬性,有時候這很有用。以下是一段代碼中的所有三種變體。

abstract class Class<V>(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 */ 
    } 
} 

也可以使用任何頂層函數和屬性。

+0

非常感謝! – Elye

+0

我喜歡你如何將所有三種可能性合併到一個代碼示例中。 –