Bhaskar Singh
12/15/2024, 4:00 PMSam
12/15/2024, 5:41 PMvar
property to a class results in the same bytecode as a Java field with a getter and a setter. Kotlin’s syntax is more concise, but the underlying machinery is the same, as are the problems it’s solving.
So, a typical Kotlin property still contains a field as part of its implementation. This is called the property’s backing field. You normally don’t need to worry about it, since it’s created automatically and invisibly. You’ll only ever see it if you choose to customize the property’s existing implicitly generated accessors. By providing your own implementation for the property’s accessors, you can also declare a property that doesn’t use a backing field at all—in the same way that you could declare accessor-like methods without a corresponding field in Java.
As for the term backing property, that’s not something created for you implicitly by Kotlin. Instead, it describes a particular way of using properties in your own classes. Specifically, if you create two properties, and customize the first property’s accessors so they pull data from the second property, you could describe the second property as a backing property for the first. This isn’t something you’d need to do very often. I’ve seen backing properties used when the public property and its private backing property need to have different types—for example when a list should be mutable within the class but read-only from outside. A future change to the language will likely make it possible to do that all as part of a single property, instead of needing two.CLOVIS
12/17/2024, 8:37 AMfinal class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
is exactly equivalent to the following Kotlin code:
class Point(
val x: Int,
val y: Int,
)
Properties aren't really a "new thing", they're just a concise way to use fields in the correct™ way more easily.
I wrote a blog post about this and other Kotlin design decisions that were inspired by Java:
https://ivan.canet.dev/blog/2024/12/16/better-java-3.html#item-16-use-public-accessors-not-public-fields