What is Kotlin backing field is used for?

Technology CommunityCategory: KotlinWhat is Kotlin backing field is used for?
VietMX Staff asked 3 years ago

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.

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.

var selectedColor: Int = someDefaultValue
        get() = field
        set(value) {
            field = value
        }