Skip to content
tezvyn:

Kotlin Delegated Properties: Reusing Getter/Setter Logic

Source: kotlinlang.orgMediumHow cards are made

Kotlin Delegated Properties: Reusing Getter/Setter Logic

Kotlin's delegated properties let you outsource a property's getter/setter logic. Instead of writing boilerplate, you reuse common patterns like lazy initialization (by lazy) or observing changes (by observable).

Why it exists

Many properties follow common patterns: their value is expensive to compute and should be deferred, or changes to them need to trigger other logic. Writing this boilerplate for every property is repetitive and error-prone. Delegated properties offer a reusable, language-level solution to these common behaviors.

The mental model

Think of a delegated property as hiring a specialist. Your class defines a property (var name: String), but it uses the by keyword to hire a delegate to manage the details of getting and setting its value. The class doesn't need to know how the value is stored or calculated; it just trusts the delegate to handle it correctly.

How it works

The syntax var p: String by Delegate() tells the compiler to redirect all reads and writes of property p to a Delegate instance. Instead of a standard backing field, the compiler calls Delegate.getValue() for reads and Delegate.setValue() for writes. Any object can be a delegate as long as it provides these required operator functions.

When to use it

Delegated properties are ideal for implementing common patterns cleanly. Three key use cases are: first, lazy initialization with by lazy { ... }, where an expensive object is created only on its first use; second, observing changes with by Delegates.observable(), which runs a block of code after a property is modified, perfect for updating UI or logging; third, vetoing changes with by Delegates.vetoable(), which can validate a new value and prevent the assignment if it's invalid.

When not to use it

For simple properties that just store a value with no special logic, a standard property (val x = 10) is more direct and performant. Using delegation for every property adds unnecessary indirection and object allocation. Stick to standard properties unless you need reusable getter/setter behavior.

One canonical example

The most common delegate is lazy. It defers the execution of a code block until the property is first accessed, and caches the result for all subsequent calls.

val lazyValue: String by lazy {
println("computed!")

"Hello" }

println(lazyValue) // Prints "computed!" then "Hello" println(lazyValue) // Prints only "Hello"

The message "computed!" is printed only once, proving the initializer block ran only on the first access. This is a powerful way to improve performance by avoiding expensive work until it's truly needed.

Interview question

What is the fundamental purpose of Kotlin's delegated properties?

  • a.To enable properties to be initialized only when they are first accessed.
  • b.To allow custom logic for getting and setting a property's value to be encapsulated and reused.Correct
  • c.To enforce immutability for properties declared with the val keyword.
  • d.To automatically generate backing fields for all properties, simplifying class definitions.
Why?

The card states that delegated properties "let you outsource a property's getter/setter logic" and offer a "reusable, language-level solution to these common behaviors." This directly aligns with encapsulating and reusing custom logic. While lazy initialization (option A) is a key use case, it's one specific application of delegation, not the fundamental purpose of the delegation mechanism itself.

Just read this? Test yourself on what you have been reading.

Read the original → kotlinlang.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on kotlin — each one lists the topics its interview covers.

See open roles