As a Java developer, the concept of a backing field is a bit foreign to me. Given:
class Sample {
var counter = 0 // the initializer value is written directly
Backing fields are good for running validation or triggering events on state change. Think of the times you've added code to a Java setter/getter. Backing fields would be useful in similar scenarios. You would use backing fields when you needed to control or have visibility over setters/getters.
When assigning the field with the field name itself, you're actually invoking the setter (i.e. set(value)
). In the example you have, this.counter = value
would recurse into set(value) until we overflow our stack. Using field
bypasses the setter (or getter) code.