Kotlin val差异getter覆盖vs赋值
我开始和Kotlin玩arround,并阅读了一些关于使用custom getter的可变val的内容。如中所述,如果结果可以更改,则不应覆盖getterKotlin val差异getter覆盖vs赋值,kotlin,getter,Kotlin,Getter,我开始和Kotlin玩arround,并阅读了一些关于使用custom getter的可变val的内容。如中所述,如果结果可以更改,则不应覆盖getter 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)
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
}
但是仅仅从指南中的用法来看,以下两种方法的区别在哪里
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 override,该值并没有被存储。getter覆盖是否与赋值不同?可能是委托还是latinit?这里的关键区别在于,在
val isEmpty get()=…
中,每次访问属性时都对主体进行求值,而在val isEmpty=…
中,在对象构造期间对右侧的表达式进行求值,结果存储在中,每次使用该属性时都会返回准确的结果
因此,第一种方法适用于每次计算结果的情况,而第二种方法适用于只计算一次并存储结果的情况。在第二个示例中,
大小是不可变的值,因此两种方法都有效
但是,每次访问isEmpty
变量时,都会计算带有重写getter的变量get()=size==0
,因此size==0
另一方面,当使用初始值设定项=size==0
时,表达式size==0
在构造过程中进行求值(在此精确检查时间和方式-),并存储到,当您访问变量时,将返回哪个值。如果getter函数示例被声明为var
,那么会有什么区别?根据文档,在上述示例中不会有任何影响。当使用val
时,不允许设置器,当使用var
时,您可以(可选)实现设置器-如果不实现设置器,则将使用默认的字段
标识符()。但是因为您实现了自定义getter,所以这个字段没有任何用处(除非您在getter中使用它)?kotlin文档没有解释。什么是支持字段?你的链接没有解释它。它是一个存储属性值的字段。它可以是可变的,也可以是不可变的(JVM术语中的final
)。