Properties
A Kotlin class doesn't have setter
or getter
methods, yet it doesn't break encapsulation by exposing private fields. The reason is that Kotlin has properties. C# is one of the languages Kotlin drew inspiration from, and the concept of properties is one of the things it took from C#. You can think of properties as fields and methods, all in one place. To the outside users of a property, the syntax looks like they are accessing a public field of a class. Internally in your class, behind a property, you can have get and set accessors or methods and a private backing field. The get
and set
methods then control how your private field is accessed, thus not breaking encapsulation.
Specifying get and set, as in our case, is optional. If you omit them, then it is implied that the property is both read and write. The compiler generates a private backing field for you in that case. You can also have get only accessor inside a property. This is then considered a read-only property and it cannot...