Search code examples
javakotlinencapsulation

Does Kotlin break the rule of encapsulation?


Variables are used public in classes using the default visibility modifier. A setter and a getter is created for every member variable, but in Kotlin you do for example:

class Person {
    var name: String = "unknown"
}

fun main(args: Array<String>) {
    val person = Person()
    person.name = "kevvex"
    println("${person.name}")
}

Is this still not breaking the rule of encapsulation due to the getter and setter being applied when using:

person.name = "kevvex"

If so, how can that be encapsulation? The variable is still public. Declaring it as private would force me to create a setter and getter to get the variable, because of the private visibility modifier.

I'm comparing to Java that often has member variables as private and a public setter and getter for every member variable.


Solution

  • I'm comparing to Java that often has member variables as private and a public setter and getter for every member variable.

    This is actually what is happening in this Kotlin code. name is not a field (what you call a member variable), it's a property with a private backing field. And if you modify its getter and setter:

    var name: String
        get() = ...
        set(value: String) { ... }
    

    the callers continue using

    person.name = "kevvex"
    

    and don't require recompilation.

    I.e. var name: String = "unknown" is exactly equivalent to Java's

    private String _name = "unknown";
    public String getName() { return _name; }
    public void setName(String name) { this._name = name; }
    

    and will even be seen from Java like that. So it breaks encapsulation to the same degree Java does.