如何使用Kotlin中的参数进行延迟初始化

在Kotlin中,我可以在下面的声明中执行不带参数的Lazy Initialization。

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

而且任何顶层的函数和属性都可以使用。