在Kotlin中,我可以执行不带参数的Lazy Initialization,如下所示.
val presenter by lazy { initializePresenter() }
abstract fun initializePresenter(): T
Run Code Online (Sandbox Code Playgroud)
但是,如果我在initializerPresenter中有一个参数,即viewInterface如何将参数传递给Lazy Initiallization?
val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) }
abstract fun initializePresenter(viewInterface: V): T
Run Code Online (Sandbox Code Playgroud)
Mic*_*ael 23
您可以使用可访问范围内的任何元素,即构造函数参数,属性和函数.您甚至可以使用其他惰性属性,这有时非常有用.以下是单个代码中的所有三个变体.
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 */
}
}
Run Code Online (Sandbox Code Playgroud)
并且也可以使用任何顶级函数和属性.
| 归档时间: |
|
| 查看次数: |
6418 次 |
| 最近记录: |