【问题标题】:How to Lazy Initialize with a parameter in Kotlin如何在 Kotlin 中使用参数进行延迟初始化
【发布时间】:2016-03-26 05:58:50
【问题描述】:

在 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

【问题讨论】:

    标签: kotlin


    【解决方案1】:

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

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

    也可以使用任何顶级函数和属性。

    【讨论】:

    • 我喜欢你如何将所有三种可能性融入一个代码示例。
    • 问题是否仍然有效。看起来,参数可以懒惰地发送
    • @Killer 你能提供一些例子/参考吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2020-03-19
    • 1970-01-01
    • 2020-05-10
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多