Search code examples
kotlingetter-setter

How to skip defined getters or setters in Kotlin


In java you can do the follwing:

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;
    }

}

But if you define a getter or a setter with logic in Kotlin you are forced to always execute this logic when accessing the field:

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)
    }

}

Is there a better way to access the field without executing the getter or setter logic than creating your own fun getBar() in Kotlin?


Solution

  • There is no possible way to skip a getter or a setter, they are intended to block the direct access of a property.

    What you can do is make a multi-reference to same value (fake-referencing):

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