Effective Kotlin: Item 16 — In public classes, use accessor methods, not public fields

As recommended by Joshua Bloch in Effective Java, you should access fields in public classes through getters and setters. Kotlin helps us achieve this by automatically generating these for any properties you define. By encapsulating the field, we have an opportunity to change the internals without breaking the external API.

For example perhaps initially your API exposes a String, but internally you now want to represent this as an Int, you could do the following:

class Example {
private var newField: Int

var oldField: String
get() {
return newField.toString()
}
set(value) {
newField = value.toInt()
}
...
}

One of the reasons for Java it is considered less important to ensure internal classes have accessors for fields is because of the code explosion you have with getters and setters. However, since Kotlin hides this from you, there is no such concern.

Kotlin introduces the @JvmField annotation to expose the field directly. However, you are advised to avoid its use following the Effective Java guidelines except when defining static constants.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store