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
都将始终打印"绿色".无论如何,支持字段都将设置为"蓝色"