Kotlin val差异getter覆盖与赋值 [英] Kotlin val difference getter override vs assignment

查看:93
本文介绍了Kotlin val差异getter覆盖与赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始与Kotlin一起玩,并阅读了有关使用自定义吸气剂的可变val的知识.如此处科特林编码约定如果结果可以改变.

I started playing arround with Kotlin and read something about mutable val with custom getter. As refered in e.g here or in the Kotlin Coding Convention one should not override the getter if the result can change.

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
}

答案中,我可以看到,对于getter覆盖,该值未存储.还有其他一些地方,getter覆盖与赋值不同吗?也许有代表或latinit?

From this answer I could see that for getter override the value is not stored. Is there something else where the getter override is different form the assignment? Maybe with delegates or latinit?

推荐答案

在第二个示例中,size是不可变值,因此两种方法均有效.

In your second example size is immutable value and therefore both ways are valid.

但是具有覆盖的getter的变体get() = size == 0 没有后备字段,因此每次访问isEmpty变量时都会评估size == 0.

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进行求值(请在此处确切地确认时间和方式-

On the other hand, when using initializer = size == 0 the expression size == 0 is evaluated during construction (check exactly when and how here - An in-depth look at Kotlin’s initializers) and stored to the backing field, of which value is then returned when you access the variable.

这篇关于Kotlin val差异getter覆盖与赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆