Kotlin val差异吸气器覆盖与分配

Fre*_*shD 10 getter kotlin

我开始和Kotlin一起玩,并通过自定义getter阅读有关可变val的内容.正如在此处或在Kotlin编码公约中所提到的,如果结果可能改变,则不应覆盖吸气剂.

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
}
Run Code Online (Sandbox Code Playgroud)

但只是从使用的角度来看,在指南中,以下两者之间存在差异

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
}
Run Code Online (Sandbox Code Playgroud)

这个答案我可以看到,对于getter覆盖,不存储该值.还有其他东西,其中getter覆盖与赋值不同吗?也许与代表或latinit?

Boj*_* P. 9

在您的第二个示例中size是不可变值,因此两种方式都是有效的.

但是,具有重写的getter的变体get() = size == 0 没有后备字段,因此size == 0每次访问isEmpty变量时都会对其进行评估.

另一方面,当使用初始化程序时= size == 0,表达式size == 0在构造期间进行评估(确切地检查何时以及如何 - 深入查看Kotlin的初始化程序)并存储到后备字段中,如果在访问变量时返回值.


hot*_*key 7

此处的主要区别在于,val isEmpty get() = ...每次访问该属性时,都会对主体进行评估,而在val isEmpty = ...对象构造过程中,对右侧的表达式进行求值时,结果将存储在后备字段中,并且每次都将返回此精确结果使用该属性。

因此,当您希望每次都计算结果时,第一种方法是合适的,而当您希望只计算一次并存储结果时,第二种方法是合适的。