Skip to content Skip to sidebar Skip to footer

Kotlin - How Can We Access Private Property With Getter And Setter? Is Access Methods Are Calling Internally?

class Sample1 { private var test = '' get() = field set(value) { field = value }} This is my class. I want to keep the property as private and have to access th

Solution 1:

Kotlin groups a field, its getter and its setter (if applicable) into the single concept of a property. When you're accessing a property, you're always calling its getter and setter, just with a simpler syntax, which happens to be the same as for accessing fields in Java. But the actual field backing the property is private, and all calls go through the getters and setters, which have the same visibility as the property itself, in your case, private. So your class would translate to this:

public final class Sample1 {

    private String test = "";

    private String getTest() { return test; }

    private void setTest(String test) { this.test = test; }

}

And your call to Sample1().text would look like this in Java (and you can actually do this from Java code that calls this Kotlin class):

new Sample1().getText();

All that to say is that the solution is to change the visibility of the property to whatever you'd set the getter and setter visibilities to in Java, for example, to the default public visibility:

class Sample1 {
    var test = ""
        get() = field
        set(value) {
            field = value
        }
}

Note that if you don't have an explicit getter and setter declared, you'll get ones automatically which do the same thing as the implementations above, so you can shorten your code to this:

class Sample1 {
    var test = ""
}

This final code is equivalent to this Java class:

public final class Sample1 {

    private String test = "";

    public String getTest() { return test; }

    public void setTest(String test) { this.test = test; }

}

Post a Comment for "Kotlin - How Can We Access Private Property With Getter And Setter? Is Access Methods Are Calling Internally?"