A backing field is compiler-managed storage for a Kotlin property's value when the property needs to retain data. A property may instead calculate its value through a custom getter. section 4.2.3 section 4.2.4
Stored versus computed properties
interface User { val nickname: String } class SubscribingUser(val email: String) : User { override val nickname: String get() = email.substringBefore('@') } class SocialUser(val accountId: Int) : User { override val nickname = getNameFromSocialNetwork(accountId) } SubscribingUser calculates nickname on every access. SocialUser computes the name during initialization and stores it in a backing field. section 4.2.3
Listing 4.20 Accessing the backing field in a setter
class User(val name: String) {
var address: String = "unspecified"
set(value: String) {
println(
"""
Address was changed for $name:
"$field" -> "$value". #1
""".trimIndent()
)
field = value #2
}
}
fun main() {
val user = User("Alice")
user.address = "Christoph-Rapparini-Bogen 23"
// Address was changed for Alice:
// "unspecified" -> "Christoph-Rapparini-Bogen 23".
}
Use the special identifier field inside an accessor to read or update the property's stored value; the setter can add logging before assigning it. section 4.2.4
The compiler generates a backing field when a property uses the default accessor or explicitly references field. Custom accessors that never use field can define a property without stored information. section 4.2.4
Listing 4.21 A property that doesn’t store information itself
class Person(var birthYear: Int) {
var ageIn2050
get() = 2050 - birthYear #1
set(value) {
birthYear = 2050 - value #2
}
}
Compare a property implemented entirely through accessors: ageIn2050 derives its value from birthYear and writes back through that other property, so it stores no independent value. section 4.2.4
