I noticed that when I have a var property with a custom get, that does not use the field identifier, a backing field is generated anyway. I checked the bytecode, and the documentation says so as well:

A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.
(emphasis is mine)

考虑一个这样的班级.由于它是var属性,因此将生成默认的set(以及支持字段):

class Banana {
    var ripeness = 1

    var color: String = "green"
        get() = when {
            ripeness > 80 -> "brown"
            ripeness > 50 -> "yellow"
            else -> "green"
        }
}

val b = Banana()
b.color = "blue"

println(b.color)

然而,无论我将color设置为什么,println都将始终打印"绿色".无论如何,支持字段都将设置为"蓝色"

推荐答案

带有未使用支持字段的"计算"100属性应为"计算"101属性.

If you are not going to use the backing field in your example then Banana.color shouldn't be a var but a val. e.g.:

class Banana {
    var ripeness = 1

    val color: String
        get() = when {
            ripeness > 80 -> "brown"
            ripeness > 50 -> "yellow"
            else -> "green"
        }
}

另一方面,如果您确实想让您的"计算"属性在某些情况下是可覆盖的,那么您将需要实际使用Backup字段.例如:

class Banana {
    var ripeness = 1

    var color: String = "green"
        get() = when {
            ripeness > 80 -> "brown"
            ripeness > 50 -> "yellow"
            else -> field
        }
}

Kotlin相关问答推荐

有什么原因,我得到一个空相关的错误在这个代码

调用即发即忘方法--哪个作用域?

Kotlin多平台(KMP)保存到文件不能在iOS上保存

我可以在kotlin/java.util.scanner中跳过分隔符而不重复吗?

Spring Boot 3:为Kotlin中的TestRestTemplate配置读取超时

使用 kotlin 流删除 map 中具有某些相似性的值

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

奇怪的 cotlin check Not Null 参数错误

Kotlin:不允许在辅助构造函数参数上使用val

如何禁用智能投射突出显示 Kotlin?

API 'variant.getJavaCompile()' 已过时

在用Kotlin编写的Android库公共API中处理R8+JvmStatic Annotation+Lambda

哪里可以找到aapt2日志(log)?

Kapt不适用于Android Studio 3.0中的AutoValue

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

具有泛型param的Kotlin抽象类和使用类型param的方法

Kotlin替换字符串中的多个单词

Kotlin类型安全类型别名

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module

如何在 firebase 数据库中使用 kotlin 协程