简体   繁体   English

如何使用Kotlin中的参数进行Lazy Initialize

[英]How to Lazy Initialize with a parameter in Kotlin

In Kotlin, I could perform Lazy Initialization without Parameter as below declaration. 在Kotlin中,我可以执行不带参数的Lazy Initialization,如下所示。

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

However, if I have a parameter in my initializerPresenter ie viewInterface , how could I pass the parameter into the Lazy Initiallization? 但是,如果我在initializerPresenter中有一个参数,即viewInterface ,我怎么能将参数传递给Lazy Initiallization?

val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) }
abstract fun initializePresenter(viewInterface: V): T

You can use any element within the accessible scope, that is constructor parameters, properties, and functions. 您可以使用可访问范围内的任何元素,即构造函数参数,属性和函数。 You can even use other lazy properties, which can be quite useful sometimes. 您甚至可以使用其他惰性属性,这有时非常有用。 Here are all three variant in a single piece of code. 以下是单个代码中的所有三个变体。

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

And any top-level functions and properties can be used as well. 并且也可以使用任何顶级函数和属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM