Getting Down in the Weeds
In Java, we have fields:
class Foo {
private int myField;
}
We make the comparison to Kotlin properties, but that is only an approximation.
In Java, sometimes we define “getter” and “setter” methods, and sometimes those adhere to “JavaBean” naming conventions:
class Foo {
private int myField;
int getMyField() {
return myField;
}
void setMyField(int newValue) {
myField = newValue;
}
}
A Kotlin property really represents the combination of these three elements:
- a field
- a getter function
- a setter function
It so happens that for simple properties — like those we have seen in this chapter and previously — those three elements have default implementations that are hidden behind the simple var
-style declaration. When we read a property’s value, we really are calling a getter function that returns the value of the property’s “backing field”. When we write a property’s value, we really are calling a setter function that sets the value of the backing field.
Some advanced Kotlin syntax — such as the “fake properties” alluded to earlier — take advantage of this, overriding the default getter and/or setter to do something else.
For most Kotlin programming, though, this is “a distinction without a difference”. Property syntax resembles accessing Java fields, so we think of properties as being equivalent to fields. However, if you later advance to the “WTF?” chapters of this book, we will return to this concept of properties really being fields with getter/setter functions.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.