1. Introduction
When you first see Delegates.observable, a natural question comes up: “Why do I need some kind of magic with by if I can just write set(value) and validate/log everything there?” It’s a fair question. The answer is also fair: observable is useful when you need a centralized reaction to assignments and don’t want to smear the same code across multiple methods or setters—for example, for logging, counting changes, or setting an “object changed” flag.
It’s important to set expectations right away: this is an overview lecture. We won’t be writing our own delegates, and we won’t dive into advanced topics like how getValue/setValue work under the hood, reflection, or multithreading subtleties. We will learn to confidently use Delegates.observable as a ready-to-use tool from the standard library.
What by means in properties
The syntax of a delegated property looks like this: val/var name: Type by <expression>. You can read it roughly as: “reading and (if var) writing this property is handled by another object—the delegate.” In the Kotlin documentation, this is explained as the property accessors being “delegated” to the delegate’s methods (getValue() and setValue()).
If you recall the previous lecture, by lazy { ... } is also a delegate (just the most popular one, which is why it can feel “special”). Delegates.observable is a different kind of delegate: it stores the value and invokes a handler after each assignment.
So it doesn’t feel like we “suddenly” jump into new syntax, here’s a small guide:
| Mechanism | What it solves | When the code runs | Is there caching? |
|---|---|---|---|
|
Write control (validation/normalization) | Every time on assignment | Depends on you |
computed property () |
Computing a representation | Every time on read | No |
|
Lazy computation | First read access | Yes (built-in) |
|
Reacting to changes | Every time on assignment (after the write) | Yes (the delegate stores the current value) |
2. How Delegates.observable works
The basic contract and when the handler fires
Delegates.observable takes an initial value and a change handler. The handler is invoked every time you assign a value to the property, with an important nuance: it is invoked after the assignment has already happened.
The handler has three parameters: “property description”, the old value, and the new value. In code it typically looks like this:
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("<no name>") { _, old, new ->
println("$old -> $new") // <no name> -> Alice, then Alice -> Bob
}
}
fun main() {
val u = User()
u.name = "Alice"
u.name = "Bob"
}
Notice: we replaced the first handler parameter with _. That’s standard practice—if a parameter isn’t needed, don’t make the code harder to read.
Two important consequences of “after assignment”.
First, inside the handler you can read the property itself and you’ll get the new value (it has already been written). This is convenient, but sometimes confusing if you expected “notify first, write later”.
Second, observable is not the place where you “stop” a bad value. If you need to block an assignment, that’s a different tool (and we’re not covering it today so we don’t sprawl into adjacent topics).
The first handler parameter and why you might need it
The first handler parameter is an object that describes the property (essentially: “metadata about the property”). The documentation shows this parameter being passed to the handler along with old/new.
We haven’t studied reflection deeply (and we don’t need to), but there’s one practical thing you can take from it: the property has a name. Sometimes that’s handy for debug logging, especially if you have several observable properties and you want a consistent message style.
Let’s make the wallet a bit more talkative:
import kotlin.properties.Delegates
class Wallet {
var balanceCents: Int by Delegates.observable(0) { prop, old, new ->
println("${prop.name}: $old -> $new") // balanceCents: 0 -> 100
}
private set
fun deposit(cents: Int) {
require(cents > 0) { "deposit must be > 0" }
balanceCents += cents
}
}
Yes, it looks like “a little bit of magic”. But in practice you treat prop.name as a neat bonus: use it if you want; if you don’t, put _.
A small look under the hood: why prop$delegate exists
A mini overview for understanding, without going into writing your own delegates. With delegation, Kotlin usually generates a hidden field that stores the delegate, and the property accessors simply call the delegate’s methods. The documentation illustrates this with an example where a field like prop$delegate appears.
If we simplify a lot, you can imagine it like this:
obj.prop = value
↓
delegate.setValue(obj, property_description, value)
↓
delegate writes the new value
↓
delegate calls the observable handler (old/new)
That’s why observable can feel “built into the language”: it’s actually just a ready-made delegate from the standard library, and the by syntax is language-level support for delegation.
The key is not to overdo it: understanding the general idea is useful, but “how to write your own delegate” is a separate topic—and we’re not going there today.
3. Practice: where observable helps—and where it gets in the way
Mini budget tracker: logging balance changes
So the examples aren’t “in a vacuum”, let’s continue our hypothetical app: a simple budget tracker (wallet) with a balance and deposit/withdraw operations. We already know how to encapsulate state: the balance can’t be changed directly, only via methods that enforce invariants.
Let’s create a Wallet class and add a reaction to balance changes: we’ll print a change log to the console. This is a typical observable scenario: observing assignment without trying to replace business logic.
import kotlin.properties.Delegates
class Wallet {
var balanceCents: Int by Delegates.observable(0) { _, old, new ->
println("balance: $old -> $new") // for example: balance: 0 -> 500
}
private set
fun deposit(cents: Int) {
require(cents > 0) { "deposit must be > 0" }
balanceCents += cents
}
}
And test it in main:
fun main() {
val w = Wallet()
w.deposit(500) // balance: 0 -> 500
w.deposit(250) // balance: 500 -> 750
}
Two useful things happen here at once. First, we keep the design correct: outside code can’t change the balance (private set). Second, the logging logic “sticks” to the property itself and doesn’t get duplicated in every method.
observable and encapsulation: where rules and checks should live
The most common beginner mistake is to see observable, get excited, and start stuffing all business logic into it: “if the new value is bad, roll it back”, “if the balance went negative—fix it”, and so on. The problem is that observable is a reaction after assignment. That means you’ve already written the value, and only then you start “fixing things”.
It’s better to keep the rules where you designed them before: in methods that change state, and/or in setters with require(...). And leave observable for side effects: logging, a change counter, setting a “dirty” flag.
For example, let’s make deposit and withdraw methods and forbid going negative. And in observable we’ll only mark that the state has changed.
import kotlin.properties.Delegates
class Wallet {
var isDirty: Boolean = false
private set
var balanceCents: Int by Delegates.observable(0) { _, old, new ->
if (old != new) isDirty = true
}
private set
fun withdraw(cents: Int) {
require(cents > 0) { "withdraw must be > 0" }
require(balanceCents >= cents) { "not enough money" }
balanceCents -= cents
}
}
And a small run:
fun main() {
val w = Wallet()
println(w.isDirty) // false
w.withdraw(0) // IllegalArgumentException (withdraw must be > 0)
}
The key idea here: we don’t “treat consequences”, we prevent them. observable only records the fact of change; it doesn’t “run” correctness.
observable vs a regular setter: what to choose
observable is not a replacement for setters. It’s a different tool.
If your goal is to normalize a string (trim, case conversion), check a range, or maintain an invariant, then a setter (or a method) is usually clearer and more straightforward. If your goal is to react to changes (log, count changes, notify), observable often makes the code more compact.
Imagine our app has a “notification volume level”, and we want to store a value from 0 to 10, and print a log on change. Let the rules live in a method, and the log live in observable.
import kotlin.properties.Delegates
class NotificationSettings {
var volume: Int by Delegates.observable(5) { _, old, new ->
println("volume: $old -> $new")
}
private set
fun setVolume(x: Int) {
require(x in 0..10) { "volume must be in 0..10" }
volume = x
}
}
Now the “class contract” reads nicely: setVolume is the only door for changes, volume can only be read, and logging is centralized.
observable in real life: a change counter
In larger projects, observable is often associated with UI: “when a field changes—update the screen”. But even in a console app it can be handy.
For example, you want to count the number of balance changes so you can show at the end: “there were N financial operations during this session”. Sure, you can increment a counter in every method. But if operations later sprawl (discounts, transfers, fees), you’ll forget to update the counter somewhere—and then you’ll be stuck wondering why the stats are lying.
With observable, you can tie the counter to the fact that the property changed:
import kotlin.properties.Delegates
class Wallet {
var changeCount: Int = 0
private set
var balanceCents: Int by Delegates.observable(0) { _, old, new ->
if (old != new) changeCount++
}
private set
fun deposit(cents: Int) {
require(cents > 0) { "deposit must be > 0" }
balanceCents += cents
}
}
Check:
fun main() {
val w = Wallet()
w.deposit(100)
w.deposit(100)
println(w.changeCount) // 2
}
Yes, it’s still a side effect. But it’s localized and clear: “each balance change increments the counter”.
4. Common mistakes when working with Delegates.observable
Mistake No. 1: putting business logic and correctness rules into the observable handler.
It’s very easy to start doing everything in the handler: checking ranges, rolling values back, “fixing” the object. The problem is that the handler is called after assignment, which means you’re working with already modified state. It’s much more reliable to keep invariants in methods (deposit/withdraw) or in a setter with require(...), and leave logging and simple reactions to observable.
Mistake No. 2: accidentally creating recursion—assigning the observed property inside the handler.
If inside the handler you do something like balanceCents = ..., you’ll trigger assignment again, then the handler again—and so on until StackOverflowError or until you start doubting what’s real. If you need to “correct” the value, that’s usually a sign you need a different design (validate before assignment), not an attempt to patch what’s already written.
Mistake No. 3: forgetting that the handler is called even when assigning the same value.
observable reacts to the assignment event itself. If you do x = x, the handler may still be called. So if you count changes or set a isDirty flag, it’s almost always useful to compare old and new and react only when there is an actual change: if (old != new) ...
Mistake No. 4: turning observable into a hidden logger that is always noisy.
Debug println calls in the handler are convenient in learning examples, but in a real project such logging quickly becomes noise. Even in a learning app, it’s better to build the habit: make logging disableable (at least via a flag), or print only important events, or limit the output.
Mistake No. 5: expecting that observable replaces encapsulation.
Sometimes it feels like: “since I observe changes, I can make a public var and let anyone modify it, and I’ll control it in the handler”. That’s a slippery slope. Observation does not replace access restriction. If the property must not be changed from the outside—use private set and mutate via methods. And let observable be your neat “sensor”, not the only guard at the door.
GO TO FULL VERSION