What is Backing Field ?
Backing field is an autogenerated field for any property which can only be used inside the accessors(getter or setter) and will be present only if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier. This backing field is used to avoid the recursive call of an accessor which ultimately prevents the StackOverflowError.
What is the need for Backing field ?
have a look at the below Kotlin code
var selectedColor: Int = someDefaultValue {
get() = selectedColor
set(value) {
this.selectedColor = value
doSomething()
}
}
The above code is calling the getter in a recursive manner if we try to get the value of selectedColor. when we call selectedColor
, it calls the getter again inside the getter which might end with a StackOverflowError.
Similar way, when we try to set the value of selectedColor it calls the same setter in a recursive way as ‘this.selectedColor’ calls the setter again from inside a setter method.
How to use Backing field ?
Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field
identifier.
Replace the variable with the keyword field
inside getter and setter
var selectedColor: Int = someDefaultValue
get() = field
set(value) {
field = value
}
Limitations while using Backing field
- The
field
identifier can only be used in the accessors of the property. - 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, in the following case there will be no backing field:
val isEmpty: Boolean
get() = this.size == 0