在Kotlin中,我可以执行不带参数的延迟初始化,如下所示。
val presenter by lazy { initializePresenter() }
abstract fun initializePresenter(): T
但是,如果我的initializerPresenter中有一个参数,即viewInterface
,我怎么能将参数传递给Lazy Initiallization?
val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) }
abstract fun initializePresenter(viewInterface: V): T
答案 0 :(得分:17)
您可以使用可访问范围内的任何元素,即构造函数参数,属性和函数。您甚至可以使用其他惰性属性,这有时非常有用。以下是一段代码中的所有三种变体。
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 */
}
}
也可以使用任何顶级函数和属性。