我開始和Kotlin一起玩arround,並用自定義getter讀了一些關於mutable val的內容。如例如here或Kotlin Coding Convention所述,如果結果可以改變,則不應該重寫吸氣劑。Kotlin val差異getter覆蓋vs作業
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
}
但是,僅僅從使用的角度作爲指導方針,其中從this答案,我可以看到,吸氣劑覆蓋的值不存儲在以下兩個
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覆蓋是不同的分配?也許與代表或拉丁美洲?