如何在Kotlin中跳过定义的吸气剂或设置器

问题描述 投票:0回答:2

在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逻辑的情况下有更好的方法来访问该字段吗?>

在Java中,您可以执行以下操作:公共类Foo {private String bar =“ text”; public void method(){//直接访问(无逻辑)System.out.println(this.bar); } / ...

kotlin getter-setter
2个回答
0
投票

无法跳过获取或设置方法,它们旨在阻止对属性的直接访问。


0
投票

在Kotlin中,后备字段(在您的情况下为私有变量)不是设计导致的。这里有一些例外说明:https://kotlinlang.org/docs/reference/properties.html#backing-fields

© www.soinside.com 2019 - 2024. All rights reserved.