0Pricing
Kotlin Academy · Lesson

Custom Getters and Setters with field

Write computed properties and custom setters using the backing field keyword.

Custom Getters and Setters with field is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Properties Are Not Just Fields

Each Kotlin property has an auto-generated getter (and for var, a setter). You can override them to add logic — validation, logging, computation.

Custom Getter

Override get() to compute the value each time it is read.

class Circle(val radius: Double) {
    val area: Double
        get() = Math.PI * radius * radius
}
fun main() {
    val c = Circle(3.0)
    println(c.area) // ~28.27
}

Computed Properties

Computed properties have no backing field — their value is calculated on every access.

class Rectangle(val w: Int, val h: Int) {
    val area get() = w * h
    val perimeter get() = 2 * (w + h)
}
fun main() {
    val r = Rectangle(3, 4)
    println("${r.area}, ${r.perimeter}") // 12, 14
}

Custom Setter with field

Inside a custom setter, field refers to the backing field — the actual storage.

class Temperature {
    var celsius: Double = 0.0
        set(value) {
            require(value >= -273.15) { "below absolute zero" }
            field = value
        }
}
fun main() {
    val t = Temperature()
    t.celsius = 25.0
    println(t.celsius)
    // t.celsius = -300.0 // throws
}

Backing Field Auto-Generated

If the getter/setter uses field, Kotlin generates a backing field. If neither does, no field is created — the property is purely computed.

class Counter {
    var count: Int = 0
        set(value) {
            println("Setting count from $field to $value")
            field = value
        }
}
fun main() {
    val c = Counter()
    c.count = 5
    c.count = 10
}

Setter with Side Effects

Use custom setters for logging, change notification, or syncing related state.

class Brightness {
    var level: Int = 50
        set(value) {
            val clamped = value.coerceIn(0, 100)
            println("Brightness -> $clamped")
            field = clamped
        }
}
fun main() {
    val b = Brightness()
    b.level = 75
    b.level = 150 // clamps to 100
    println(b.level)
}

Private Setter

Mark the setter private to expose a read-only API while allowing internal mutation.

class Score {
    var value: Int = 0
        private set
    fun increment() { value++ }
    fun reset() { value = 0 }
}
fun main() {
    val s = Score()
    s.increment(); s.increment()
    println(s.value) // 2
    // s.value = 100 // ERROR: setter is private
}

Validation in Setter

Custom setters are the natural home for input validation.

class Email {
    var address: String = ""
        set(value) {
            require(value.contains("@")) { "invalid email" }
            field = value
        }
}
fun main() {
    val e = Email()
    e.address = "ada@example.com"
    println(e.address)
}

Getter with Logic

Getters can transform stored state — e.g. format a stored value or apply default fallback.

class Profile(_name: String?) {
    var rawName: String? = _name
    val displayName: String
        get() = rawName ?: "(unset)"
}
fun main() {
    val p = Profile(null)
    println(p.displayName) // (unset)
}

Comparing val and var

val properties have only a getter (no setter); var properties have both.

class Box {
    val readOnly: Int get() = 42
    var readWrite: Int = 0
}
fun main() {
    println(Box().readOnly)
    val b = Box(); b.readWrite = 5; println(b.readWrite)
}

Common Mistake: Recursion

Do not use the property name inside its own accessor — it causes infinite recursion. Use field instead.

class Wrong {
    var x: Int = 0
        set(value) {
            // x = value // INFINITE RECURSION — calls setter again
            field = value // CORRECT
        }
}
fun main() {
    val w = Wrong(); w.x = 42; println(w.x)
}

Quick Check

Inside a custom setter, what does the identifier field refer to?

Recap

Override get() and set() to add logic to property access. Use field inside accessors to read/write the backing field. Mark setters private for read-only public APIs; use computed properties (no backing field) when value is always derived.

Frequently asked questions

Is the “Custom Getters and Setters with field” lesson free?

Yes — the full text of “Custom Getters and Setters with field” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Custom Getters and Setters with field”?

Write computed properties and custom setters using the backing field keyword. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Custom Getters and Setters with field” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Primary Constructor and Property Parameters
  2. init Blocks and Initialization Order
  3. Custom Getters and Setters with field
  4. lateinit and Lazy Initialization
← Back to Kotlin Academy