Backing Fields and Backing Properties in Kotlin
Backing Fields and Backing Properties in Kotlin
Kotlin properties provide a concise syntax for declaring fields with accessors. Behind this syntax, two mechanisms manage the actual storage of property values: backing fields and backing properties. A backing field is an implicit storage variable generated by the compiler when a property uses custom accessors with the field keyword. A backing property is an explicitly declared private variable that stores the value while a public property exposes controlled access. Understanding the distinction is important for writing idiomatic Kotlin and making informed decisions about encapsulation. By the end of this lesson, you will be able to:
- Explain when the Kotlin compiler generates a backing field for a property.
- Use the
fieldidentifier in custom getters and setters to access the backing field. - Implement backing properties for advanced encapsulation patterns.
- Identify the common pattern of exposing
StateFlowthrough a backing property in ViewModels.
Backing Fields
A backing field is an implicit storage variable that the Kotlin compiler generates for a property when the property's accessor uses the field keyword. It stores the actual value of the property and is only accessible within the getter and setter.
var name: String = "Default"
get() = field.uppercase()
set(value) {
field = value.trim()
}
In this example, field refers to the backing field that holds the raw String value. The getter returns the value in uppercase, and the setter trims whitespace before storing. Without the field keyword, accessing the property name inside its own getter or setter would cause infinite recursion.
The compiler generates a backing field only when it is needed. A property with a custom getter that does not reference field and has no initializer does not get a backing field:
val fullName: String
get() = "$firstName $lastName" // no backing field generated
Backing Properties
A backing property is an explicitly declared private variable that stores the actual data, while a separate public property provides controlled read or write access. This pattern gives complete control over the internal representation and the exposed API.
private var _age: Int = 0
var age: Int
get() = _age
set(value) {
if (value >= 0) _age = value
}
The _age property is the backing property. It holds the actual value and is only accessible within the class. The public age property delegates to _age through custom accessors, adding validation logic in the setter.
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor