Kotlin

Backing Fields with Custom get/set

admin by @admin ADMIN
4h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`field` is the implicit backing storage inside a property's getter/setter. Lets you wrap simple storage with validation, normalization, or change tracking — without writing a separate private field.
Kotlin
Raw
class User {
    var email: String = ""
        set(value) {
            require("@" in value) { "not an email: $value" }
            field = value.lowercase().trim()             // `field` is the backing storage
        }

    var age: Int = 0
        set(value) {
            require(value in 0..150) { "unreasonable age: $value" }
            field = value
        }
        get() {
            println("[read age]")                         // observe reads
            return field
        }

    val fullName: String                                  // no backing field — pure compute
        get() = "$firstName $lastName"

    var firstName: String = ""
    var lastName: String  = ""
}

fun main() {
    val u = User().apply {
        email     = "  ALICE@x.COM  "                    // normalized to "alice@x.com"
        firstName = "Alice"
        lastName  = "Example"
    }
    println(u.email)                                      // alice@x.com
    println(u.fullName)                                   // Alice Example
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.