我开始和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?
在您的第二个示例中size是不可变值,因此两种方式都是有效的.
但是,具有重写的getter的变体get() = size == 0 没有后备字段,因此size == 0每次访问isEmpty变量时都会对其进行评估.
另一方面,当使用初始化程序时= size == 0,表达式size == 0在构造期间进行评估(确切地检查何时以及如何 - 深入查看Kotlin的初始化程序)并存储到后备字段中,如果在访问变量时返回值.
| 归档时间: |
|
| 查看次数: |
852 次 |
| 最近记录: |