问题描述
我开始与Kotlin一起玩,并阅读了有关使用自定义吸气剂的可变val的知识.如此处或科特林编码约定如果结果可以改变.
I started playing arround with Kotlin and read something about mutable val with custom getter. As refered in e.g here or in the Kotlin Coding Convention one should not override the getter if the result can change.
class SampleArray(val size: Int) {
val isEmpty get() = size == 0 // size is set at the beginning and does not change so this is ok
}
class SampleArray(var size: Int) {
fun isEmpty() { return size == 0 } // size is set at the beginning but can also change over time so function is prefered
}
但是仅从指南中的用法角度来看,以下两者之间有何区别
But just from the perspective of usage as in the guidelines where is the difference between the following two
class SampleArray(val size: Int) {
val isEmpty get() = size == 0 // size can not change so this can be used instad of function
val isEmpty = size == 0 // isEmpty is assigned at the beginning ad will keep this value also if size could change
}
从此答案中,我可以看到,对于getter覆盖,该值未存储.还有其他一些地方,getter覆盖与赋值不同吗?也许有代表或latinit?
From this answer I could see that for getter override the value is not stored. Is there something else where the getter override is different form the assignment? Maybe with delegates or latinit?
推荐答案
在第二个示例中,size
是不可变值,因此两种方法均有效.
In your second example size
is immutable value and therefore both ways are valid.
但是具有覆盖的getter的变体get() = size == 0
没有后备字段,因此每次访问isEmpty
变量时都会评估size == 0
.
However variant with overridden getter get() = size == 0
has no backing field and therefore size == 0
is evaluated every time you access isEmpty
variable.
另一方面,在使用初始化程序= size == 0
时,会在构造过程中对表达式size == 0
进行求值(请在此处确切地确认时间和方式-深入了解Kotlin的初始化程序),并存储到备用字段,然后在访问变量时返回其值.
On the other hand, when using initializer = size == 0
the expression size == 0
is evaluated during construction (check exactly when and how here - An in-depth look at Kotlin’s initializers) and stored to the backing field, of which value is then returned when you access the variable.
这篇关于Kotlin val差异getter覆盖与赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!