Sermilion
Sermilion

Reputation: 2048

Should properties of class in Kotlin be private and how to access them?

Aloha! While reading Kotling Language Reference I noticed that the keyword "private" for properties of a class is never used (always default which is public). It also said that getters and setters are generated automatically. So I created class and made its fields private. However, when I create object of the class, I cannot see the fields and no setters and getters are available, unless I write them myself. So what's the rule here? Leave visibility modifier default (public) or make them private and provide mutator methods? Thank you.

Upvotes: 3

Views: 3693

Answers (1)

yole
yole

Reputation: 97308

The whole idea of a property is that it encapsulates a field and its accessors in a single entity. If you need to be able to access and modify a property of a class from the outside, you should keep the property public. If you need to be able to read from the outside but not update it, you can define a public property with a private accessor.

Changing a default accessor to a custom one will not affect the clients of your class, because under the hood the compiler will always generate accessor methods, and the clients of the class will use those methods and will not access the underlying field directly.

You should never write explicit getter or mutator methods which are separate from the property accessors.

Upvotes: 10

Related Questions