Part 15 / Topic 2 of 6
Properties and backing fields in bytecode
A Kotlin val/var is not a Java field with public access -- it's a property: a private
backing field plus generated accessor methods, exactly like the hand-written getter/setter
pattern Part 7 taught before Kotlin had sugar for it.
class Account(initialBalanceInr: Double) {
var balanceInr: Double = initialBalanceInr
private set // public getter, private setter
val isOverdrawn: Boolean // no backing field: just a getter
get() = balanceInr < 0.0
lateinit var branchCode: String // no field until this line runs
fun deposit(amountInr: Double) {
balanceInr += amountInr
}
}
$ javap -p out/Account.class
public final class Account {
private double balanceInr;
public java.lang.String branchCode;
public Account(double);
public final double getBalanceInr();
public final boolean isOverdrawn();
public final java.lang.String getBranchCode();
public final void setBranchCode(java.lang.String);
public final void deposit(double);
public final void withdraw(double);
}
Three things worth noticing:
- No
setBalanceInrat all.private setmakes the setter private to the class, and nothing outsideAccountcould ever call it -- so the compiler doesn't generate it. If some method insideAccounthad called the setter explicitly, it would still not appear, because of the next point. deposit'sbalanceInr += amountInrnever calls a setter, not even the private one.javap -condepositshows a plaingetfield/putfieldpair straight on the backing field:
Inside the class that owns a property, Kotlin always touches the backing field directly -- the getter/setter exist for outside callers only.public final void deposit(double); Code: 0: aload_0 1: aload_0 2: getfield #13 // Field balanceInr:D 5: dload_1 6: dadd 7: putfield #13 // Field balanceInr:D 10: returnisOverdrawnhas no backing field whatsoever.javap's field list has onlybalanceInrandbranchCode;isOverdrawnis purely a computedgetter. Avalorvaronly gets a backing field if the property actually stores something (an initializer, orfieldused inside a custom accessor) -- aget()-only computed property never does.
lateinit var branchCode: String compiles to a plain, non-final, non-null-checked public
field (see the javap listing above: no private, no final) -- Kotlin trades away its usual
null-safety checks on that one property, in exchange for letting you declare it before you have
a value. Reading it before assignment doesn't return null (the type is non-nullable String);
it throws:
reading branchCode before assignment: UninitializedPropertyAccessException
And the data class recap from Part 9: copy(), equals(), hashCode(), toString() are all
generated methods, not hand-written -- javap -p on any data class lists component1(),
component2(), copy(...), and a copy$default(...) overload that fills in omitted arguments.
Full program: examples/02_properties_and_backing_fields.kt.
Done here? The practice set for Part 15 — including the solutions — is on the part page.