kotlin - 如何在Kotlin中跳过定义的getter或setter

标签 kotlin getter-setter

在Java中,您可以执行以下操作:

public class Foo {

    private String bar = "text";

    public void method() {
        // direct access (no logic)
        System.out.println(this.bar);
    }

    // only if you access the object from the outside
    // you are forced to use the getter with some logic in it
    public String getBar() {
        System.out.println(this.bar);
        return this.bar;
    }

}

但是,如果您在Kotlin中使用逻辑定义了一个getter或setter方法,则在访问该字段时必须始终执行以下逻辑:

class Foo {

    var bar: String = "text"
        get() {
            println(field)
            return field
        }
        private set

    fun method() {
        // this also executes the getter
        // Is it possible to skip the getter
        // and directly access the field?
        println(this.bar)
    }

}

是否有比在Kotlin中创建自己的fun getBar()更好的方法而不执行getter或setter逻辑呢?

最佳答案

无法跳过getter或setter,因为它们旨在阻止对属性的直接访问。

您可以做的是对同一值进行多重引用(伪引用):

private var _bar: String = "text"
var bar
    get() {
        // some operations intercepting the getter
        return _bar
    }

// direct access
_bar
// intercepted access public field
bar

关于kotlin - 如何在Kotlin中跳过定义的getter或setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61459289/

相关文章:

JavaScript - 对象原型(prototype)中的 Getter/Setter 不起作用。 Getter 返回最后一个元素

kotlin - 我把 token 放到 Kotlin 的地方

java - 如何不使用 getter 和 setter

java - Spring:@Value 在其他类中使用 lombok

java - Java 类中的 Scala getter 和 setter

kotlin - Ktor:如何在路由处理程序中检查身份验证?

serialization - Kotlin 数据类使用 GSON 动态创建其字段的 json

maven - Kotlin maven 插件编译顺序

java - 当Android方法被贬值时我该怎么办?

python - 调用属性 getter、setter、deleter - Python