When is a backing field generated in Kotlin?

Viewed 118

Quoting Kotlin documentation on 'Backing properties'.

A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.

For example, there would be no backing field in the following case:

val isEmpty: Boolean
   get() = this.size == 0

At least one of the accessors (setter) is using the default implementation, then why would there be no backing field in the above case?

1 Answers

At least one of the accessors (setter) is using the default implementation

The example property is a val, so there is no setter. The only accessor is the getter, and that one doesn't use the default implementation, so no backing field.

I agree it would have been clearer if they started with a var example, but this example is definitely worth noting to clarify how it works for vals.

Related