Backing Field in Kotlin
--
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.
This post was originally posted at https://agrawalsuneet.github.io/blogs/backing-field-in-kotlin/
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