What is Backing Field in Kotlin: Simple Explanation and Example
backing field is a hidden field that stores the actual value of a property when you use custom getters or setters. It allows you to access the stored value inside these accessors using the keyword field.How It Works
Imagine you have a box where you keep a value. When you create a property in Kotlin, this box is created automatically to hold the value. Normally, Kotlin handles this box for you behind the scenes.
But when you want to control how the value is read or changed, you write custom getter or setter functions. Inside these functions, you still need a way to access the original box to get or set the value. This is where the backing field comes in.
The backing field is like a secret storage inside the property that you can reach only inside the getter or setter using the keyword field. This helps avoid infinite loops when you read or write the property inside its own getter or setter.
Example
This example shows a property with a custom setter that uses the backing field to store the value safely.
class Person { var name: String = "" set(value) { if (value.isNotBlank()) { field = value // backing field stores the actual value } } } fun main() { val person = Person() person.name = "Alice" println(person.name) // prints Alice person.name = "" // empty string ignored println(person.name) // still prints Alice }
When to Use
Use backing fields when you want to customize how a property value is read or written but still need to store the value internally. For example:
- Validating input before saving it
- Adding side effects when a value changes
- Controlling access to the property value
Backing fields are only available inside property accessors (getters/setters). If you try to use field outside them, it won’t work.
Key Points
- A backing field stores the actual value of a property.
- It is automatically created by Kotlin when you use custom getters or setters.
- You access it inside accessors using the keyword
field. - It prevents infinite recursion when reading or writing the property inside its own getter or setter.
- Backing fields are not accessible outside property accessors.