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

Please continue reading at https://agrawalsuneet.github.io/blogs/backing-field-in-kotlin/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

https://agrawalsuneet.github.io/