我开始和Kotlin玩arround,并通过custom getter阅读了一些关于可变val的内容.如hereKotlin 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
}

But just from the perspective of usage as in the guidelines where is the difference between the following two

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 override的值没有被存储.getter覆盖是否与赋值不同?也许是代表或是拉丁语?

推荐答案

在第二个例子中,size是不可变的值,因此这两种方法都是有效的.

However variant with overridden getter get() = size == 0 has no backing field and therefore size == 0 is evaluated every time you access isEmpty variable.

另一方面,当使用初始化器= size == 0时,表达式size == 0在构造期间求值(请准确地判断此处-An in-depth look at Kotlin’s initializers的时间和方式),并存储到backing field,然后在访问变量时返回backing field的值.

Kotlin相关问答推荐

如何在Kotlin的嵌套作用域中解析对此的引用

如何在 Big Data 中使用Inc过滤器?

只能在元素区域中点击的Jetpack Compose列

如何确保Kotlin子类已完成初始化?

S使用MAP和ElseThrow的习惯用法是什么?

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

CompositionLocal 究竟如何以及何时隐式设置值?

通用接口继承

为 Gradle 子项目配置 Kotlin 扩展

奇怪的 cotlin check Not Null 参数错误

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

对列表中数字的子集求和

IntelliJ 不会根据 ktlint 的期望对 Kotlin 导入进行排序

在协程中等待侦听器内的数据

Kotlin如何分派invoke操作符?

Kapt不适用于Android Studio 3.0中的AutoValue

Kotlin:如何修改成对的值?

Kotlin:具有多个不同类型设置器的单个属性

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

如何在不绑定ViewModel(MVVM)中的UI的情况下使用android导航?