9

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.

kevvex
  • 305
  • 3
  • 12
  • You can change the behaviour of the getter and setter if you want. They're still methods protecting the variable. They're just called in a more convenient way. – khelwood Jul 05 '18 at 13:36
  • 1
    Exposing an internal field of a class, regardless of how its implemented - with a getter or not - is **always breaking encapsulation**. – Michael Jul 05 '18 at 13:54

2 Answers2

11

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
1

You can create public variable but only with private setter

var name: String = "unknown"
private set

Additionaly you can edit how your get or set behaves, just like in Java. There is no problem with encapsulation, Kotlin makes "POJOs" creation much easier by creating "default setters / getters" as public ones

Janusz Hain
  • 597
  • 5
  • 18