如何使用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 */ } }
而且任何顶层的函数和属性都可以使用。
- 在Kotlin中实例化通用数组
- Kotlin的可玩性和LiveData
- Android不确定ProgressBar不显示
- 我如何继承KDoc文档?
- Kotlin,Java,multidex,Dagger 2,Butterknife和Realm:transformClassesWithMargingForDebug:重复条目:org / jetbrains / annotations / NotNull.class
- 例外:尽管我在另一个线程上进行了subsribed,但不能在UI线程上调用blockingConnect
- Anko中的复杂引力
- 在Kotlin中调用子程序
- 匕首与Kotlin上的Mvp – Android