gpt4 book ai didi

Kotlin val 差异 getter 覆盖与分配

转载 作者:IT老高 更新时间:2023-10-28 13:35:45 26 4
gpt4 key购买 nike

我开始玩 Kotlin 并阅读了一些关于使用自定义 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 override 与分配不同?也许与代表或拉丁?

最佳答案

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

但是,具有覆盖 getter get() = size == 0 has no backing field 的变体,因此每次访问 isEmpty 时都会评估 size == 0 > 变量。

另一方面,当使用初始化器 = size == 0 时,表达式 size == 0 在构造过程中被评估(准确检查何时以及如何在这里 - An in-depth look at Kotlin’s initializers )并存储到 backing field 中,然后在访问变量时返回其中的值。

关于Kotlin val 差异 getter 覆盖与分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45433608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com