在Kotlin中,我可以执行不带参数的延迟初始化,如下所示。

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

但是,如果我在initializerPresenter中有一个参数,即viewInterface,如何将参数传递给惰性初始化?
val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) }
abstract fun initializePresenter(viewInterface: V): T

最佳答案

您可以使用可访问范围内的任何元素,即构造函数参数,属性和函数。您甚至可以使用其他惰性属性,有时这会很有用。这是在单个代码中的所有三个变体。

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 */
  }
}

也可以使用任何顶级功能和属性。

10-02 05:59