本文介绍了Kotlin:使用自定义设置器时没有Lateinit的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的活动中,我有一个不应为空且具有自定义设置器的字段.我想在我的onCreate方法中初始化该字段,所以我在变量声明中添加了lateinit.但是,显然您目前无法执行此操作: https://discuss.kotlinlang.org/t/lateinit-modifier-is-not-allowed-on-custom-setter/1999 .

In my activity I have a field that should be non-nullable and has a custom setter. I want to initialize the field in my onCreate method so I added lateinit to my variable declaration. But, apparently you cannot do that (at the moment): https://discuss.kotlinlang.org/t/lateinit-modifier-is-not-allowed-on-custom-setter/1999.

这些是我可以看到的解决方法:

These are the workarounds I can see:

  • 以Java方式执行.使该字段可为空,并使用null对其进行初始化.我不想那样做.
  • 使用类型的默认实例"初始化字段.那就是我目前正在做的.但这对于某些类型来说太昂贵了.

有人可以推荐一种更好的方法(不涉及删除自定义设置器)吗?

Can someone recommend a better way (that does not involve removing the custom setter)?

推荐答案

用可为空的属性支持的属性替换它:

Replace it with a property backed by nullable property:

    private var _tmp: String? = null
    var tmp: String
        get() = _tmp!!
        set(value) {_tmp=value; println("tmp set to $value")}

或这样,如果您希望它与lateinit语义保持一致:

or this way, if you want it to be consistent with lateinit semantics:

private var _tmp: String? = null
var tmp: String
    get() = _tmp ?: throw UninitializedPropertyAccessException("\"tmp\" was queried before being initialized")
    set(value) {_tmp=value; println("tmp set to $value")}

这篇关于Kotlin:使用自定义设置器时没有Lateinit的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 01:21