Sobes.tech
Middle

How to use 'backing fields' in Kotlin?

sobes.tech AI

Answer from AI

Helper fields ('backing fields') are automatically generated by the compiler when using standard getters/setters and do not require explicit declaration. They are used to store the value of a property.

Explicit use of 'backing fields' is required in rare cases, for example, when you need to customize the getter or setter and refer to the property value itself, rather than the getter call, which could lead to recursion.

To explicitly access the 'backing field' inside a getter or setter, the identifier field is used.

class MyClass {
    var counter = 0 // The compiler will generate a backing field for this property
        set(value) {
            // Condition check before assignment
            if (value >= 0) {
                // Explicit access to the backing field
                field = value
            }
        }
}

A 'backing field' is not generated for a property if there is no property that uses it (for example, for abstract properties or interface properties), or if the getter and setter are fully customized and do not use the compiler-generated 'backing field'.

Example where the 'backing field' is not generated:

interface MyInterface {
    val abstractProperty: String // No backing field
}

class AnotherClass {
    val computedProperty: Int
        get() = (1 + 2) // Getter does not use a backing field, so none is generated
}
How to use 'backing fields' in Kotlin? — Kotlin - sobes.tech