【发布时间】:2018-01-08 01:43:29
【问题描述】:
我开始使用 Kotlin 玩 arround,并阅读了一些关于使用自定义 getter 的 mutable val 的内容。如 here 或 Kotlin Coding Convention 中所述,如果结果可以更改,则不应覆盖 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) {
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
}
从this 的答案我可以看到,对于 getter 覆盖,值没有被存储。还有其他什么地方 getter 覆盖与分配不同吗?也许与代表或拉丁?
【问题讨论】: