如何在Kotlin中使用参数进行延迟初始化 [英] How to Lazy Initialize with a parameter in Kotlin

查看:290
本文介绍了如何在Kotlin中使用参数进行延迟初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Kotlin, I could perform Lazy Initialization without Parameter as below declaration.

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

但是,如果我在initializerPresenter中有一个参数,即viewInterface,如何将参数传递给惰性初始化?

However, if I have a parameter in my initializerPresenter i.e. viewInterface, how could I pass the parameter into the 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.

这篇关于如何在Kotlin中使用参数进行延迟初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆