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:

  • Do it the Java way. Make the field nullable and initialize it with null. I don't want to do that.
  • 使用该类型的"默认实例"初始化该字段.我现在就是这么做的.但对某些型号来说太贵了.

有人能推荐一个更好的方法(不需要删除自定义设置器)吗?

推荐答案

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个语义一致:

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相关问答推荐

KTOR';S函数`staticResources`在Kotlin本机目标上不可用

kotlin 父类具有依赖于抽象变量的变量

按钮无法在 Android Studio 上打开新活动

如何使用 Mockk 模拟返回值类的 Kotlin 函数类型?

Kotlin 启动与启动(Dispatchers.Default)

如何在 kotlin 中创建自定义迭代器并添加到现有类?

在 Kotlin 协程中切换 IO 和 UI 的正确方法是什么?

为什么 Kotlin 的 null 安全性不能与局部变量初始化器一起正常工作?

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

在 SplashActivity 中显示的 Firebase 应用内消息.如何在 MainActivity 中显示它?

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

调用单元测试验证伴随对象方法

如何通过反射使用 Kotlin 对象

Kotlin JVM 和 Kotlin Native 有什么区别?

Tornadofx - 如何在每个实例上将参数传递给 Fragment

Kotlin协程无法处理异常

无法解决:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1

Dagger +Kotlin 不注入

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

判断EditText是否为空kotlin android