Well, time for a history lesson!
Basically, the Android world (and every Java developer until records are a thing) have been stuck with needing to use the private field with getter and setter methods pattern for quite some time. When Kotlin came around, the team wanted to massively remove boilerplate, and so they had that pattern built into the language and automatically generated. And so whenever you write this:
class Example {
val myAmazingValue: String = ""
}
Under the hood Kotlin compiles it down to this Java code:
public class Example {
private String _myAmazingValue = ""
public String getMyAmazingValue() {
return _myAmazingValue
}
public void setMyAmazingValue(String value) {
_myAmazingValue = value
}
}
Now this might seem like a performance problem, right? Wrong. method calls have very little overhead on the JVM, and whenever the JIT compiler notices a very small getter or setter like that, it just inlines it automatically. That’s because this pattern is heavily used on the JVM, and so in reality Kotlin doesn’t add any overhead at all by doing that. (Fun fact, you can actually define a property as being a public field instead of the getter/setter combination by annotating it with @JvmField
, this is provided for compatibility reasons, but most of the time you should go with the default behavior.)
This, when combined with data class
es, makes it incredibly easy to define a POJO (a POKO? idk lol) that automatically has all the getters and setters that you want. This also allows you to easily add getters and setters to any properties later on, because virtually every Kotlin library and consumer calls getters and setters. This also makes the syntax quite pleasant when working with properties.