Kotlin delegation
Delegation is a fundamental design pattern: one object forwards a request to another object for handling.
Kotlin supports delegation directly with the by keyword; the compiler generates the forwarding code automatically, which is far more concise than writing a delegate class by hand.
Kotlin delegation comes in two forms: class delegation and property delegation. This chapter covers each in turn and explains how the compiler translates them.
Class delegation
Class delegation is written by adding : Interface by delegate after the class header; the compiler generates a forwarding implementation for every method of the interface.
Example
interface
Base
{
fun print
(
)
}
// The class being delegated to
class
BaseImpl
(
private
val x
:
Int
)
:
Base
{
override fun print
(
)
{
println
(
"BaseImpl: $x"
)
}
}
// Derived delegates the implementation of the Base interface to the constructor parameter b
class
Derived
(
b
:
Base
)
:
Base by b
fun main
(
)
{
val b
=
BaseImpl
(
10
)
Derived
(
b
)
.
(
)
// What actually gets called is b.print()
}
The output is:
BaseImpl: 10
The compiler stores b in the Derived instance and generates all methods of the Base interface, forwarding them to b.
You can override a method in Derived to replace the delegate's behavior.
Example
interface
Base
{
fun print
(
)
fun name
(
)
:
String
}
class
BaseImpl
(
private
val x
:
Int
)
:
Base
{
override fun print
(
)
=
println
(
"BaseImpl: $x"
)
override fun name
(
)
=
"BaseImpl"
}
class
Derived
(
b
:
Base
)
:
Base by b
{
// Only name() is overridden; print() is still forwarded to b
override fun name
(
)
=
"Derived"
}
fun main
(
)
{
val d
=
Derived
(
BaseImpl
(
10
)
)
d.
(
)
println
(
d.
name
(
)
)
}
The output is:
BaseImpl: 10
Derived
Property delegation
Property delegation hands the reading and writing of a property to another object, with the syntax val or var propertyName: Type by delegateExpression.
A property delegate does not need to implement any interface, but it must provide getValue(), and var properties additionally need setValue().
Example
import
kotlin.reflect.KProperty
class
Example
{
// Both reads and writes of the property are delegated to the Delegate instance
var p
:
String
by
Delegate
(
)
override fun toString
(
)
=
"Example"
}
class
Delegate
{
// thisRef is the object that owns the property, and property describes the property itself
operator fun getValue
(
thisRef
:
Any
?
, property
:
KProperty
<*>
)
:
String
{
return
"$thisRef read the property ${property.name}"
}
operator fun setValue
(
thisRef
:
Any
?
, property
:
KProperty
<*>
, value
:
String
)
{
println
(
"${property.name} of $thisRef was assigned $value"
)
}
}
fun main
(
)
{
val e
=
Example
(
)
println
(
e.
p
)
// Accessing the property calls getValue()
e.
p
=
"RUNOOB"
// Assigning calls setValue()
}
The output is:
Example 读取了属性 p
Example 的 p 被赋值为 RUNOOB
Signature requirements for getValue and setValue
These two methods of the delegate must carry the operator keyword, and their parameters and return values have strict constraints.
| Method | Applicable properties | Parameters | Return value requirement |
|---|---|---|---|
| getValue() | val and var | thisRef is the property owner type or a supertype of it; property is KProperty<*>, or a supertype of it | The property type or a subtype of it |
| setValue() | var only | Append value after the parameters of getValue, of the property type or a supertype of it | None (returns Unit) |
For extension properties, thisRef refers to the type being extended.
The standard delegate lazy
The Kotlin standard library ships with common delegate factory functions, and lazy() is the most widely used one.
It takes a lambda and returns a Lazy
Example
val lazyValue
:
String
by lazy
{
println
(
"computed!"
)
// Prints only on the first access
"Hello"
}
fun main
(
)
{
println
(
lazyValue
)
// First access, triggering initialization
println
(
lazyValue
)
// Second access, returning the cached value
}
The output is:
computed!
Hello
Hello
Local variables can also be delegated with lazy, a feature available since Kotlin 1.1.
LazyThreadSafetyMode
The optional second parameter of lazy() controls initialization behavior under multithreading; the default is SYNCHRONIZED.
| Mode | Behavior | Applicable scenarios |
|---|---|---|
| SYNCHRONIZED | Locking ensures only one thread performs initialization while others block and wait | The default value, a general choice in multithreaded environments |
| PUBLICATION | Allows concurrent initialization; the first result to return wins | For expensive initialization where repeated execution is acceptable |
| NONE | No synchronization, with no guarantee of initializing only once | Use only in single-threaded code, highest performance |
Example
import
kotlin.LazyThreadSafetyMode
fun main
(
)
{
// Specify the thread-safety mode explicitly
val config
:
String
by lazy
(
LazyThreadSafetyMode.
PUBLICATION
)
{
println
(
"Performing initialization"
)
"www.runoob.com"
}
println
(
config
)
println
(
config
)
}
The output is:
执行初始化
www.runoob.com
www.runoob.com
Note:The default SYNCHRONIZED mode makes all threads wait synchronously on first access; if the initialization logic may throw, a later access retries initialization, so an exception does not leave the property permanently unusable.
Observable properties: observable and vetoable
Delegates.observable() calls back after every assignment, which suits the observer pattern.
It takes an initial value and a callback; the callback has three parameters: the property object, the old value, and the new value.
Example
import
kotlin.properties.Delegates
class
User
{
// The callback runs after every assignment
var name
:
String
by Delegates.
observable
(
"Initial value"
)
{
prop, old,
new
->
println
(
"${prop.name}:$old -> $new"
)
}
}
fun main
(
)
{
val user
=
User
(
)
user.
name
=
"First assignment"
user.
name
=
"Second assignment"
}
The output is:
name:初始值 -> 第一次赋值
name:第一次赋值 -> 第二次赋值
Delegates.vetoable() calls back before the assignment: returning true allows the write, while returning false rejects it.
Example
import
kotlin.properties.Delegates
class
User
{
// Only allow writes when the value is between 0 and 150
var age
:
Int by Delegates.
vetoable
(
0
)
{
_, _,
new
->
new
in
0
..
150
}
}
fun main
(
)
{
val user
=
User
(
)
user.
age
=
25
println
(
user.
age
)
user.
age
=
1
// Rejected, stays 25
println
(
user.
age
)
user.
age
=
200
// Rejected, stays 25
println
(
user.
age
)
}
The output is:
25
25
25
Storing properties in a map
Delegating properties to a Map instance is a common technique, especially convenient when parsing JSON or handling dynamic data.
When delegating to a Map, the property name is used as the key to look up the value.
Example
class
Site
(
val map
:
Map
<
String
,
Any
?>
)
{// The property name name corresponds to the "name" key in the map
val name
:
String
by map
val url
:
String
by map
}
fun main
(
)
{
val site
=
Site
(
mapOf
(
"name"
to
"Runoob Tutorial"
,
"url"
to
"www.runoob.com"
)
)
println
(
site.
name
)
println
(
site.
url
)
}
The output is:
Runoob Tutorial
www.runoob.com
If the delegated property is var, the Map must be a MutableMap, and assignments are written straight back to the map.
Example
class
Site
(
val map
:
MutableMap
<
String
,
Any
?>
)
{var name
:
String
by map
var url
:
String
by map
}
fun main
(
)
{
val map
=
mutableMapOf
<
String
,
Any
?>
(
"name"
to"Runoob Tutorial"
,
"url"
to
"www.runoob.com"
)
val site
=
Site
(
map
)
println
(
site.
name
)
site.
name
=
"RUNOOB"
// Write back to the map
println
(
site.
name
)
println
(
map
[
"name"
]
)
// The map itself is modified as well
}
The output is:
Runoob Tutorial
RUNOOB
RUNOOB
Delegates.notNull
Some properties cannot have their value determined at initialization time, and Delegates.notNull() is designed for that case.
It lets you declare a property first and assign it later, but reading it before assignment throws an exception.
Example
import
kotlin.properties.Delegates
class
Foo
{
// Declare without a value and assign at runtime
var notNullBar
:
String
by Delegates.
notNull
<
String
(
)
}fun main
(
)
{
val foo
=
Foo
(
)
// The instance must be created first
foo.
notNullBar
=
"bar"
// Only read after assignment
println
(
foo.
notNullBar
)
}
The output is:
bar
If you skip the assignment and read directly, the program throws an IllegalStateException.
Example
import
kotlin.properties.Delegates
class
Foo
{
var notNullBar
:
String
by Delegates.
notNull
<
String
(
)
}fun main
(
)
{
val foo
=
Foo
(
)
println
(
foo.
notNullBar
)
// Read before assignment, throws an exception
}
The output is as follows (stack trace omitted):
Exception in thread "main" java.lang.IllegalStateException: Property notNullBar should be initialized before get.
Note:Delegates.notNull() It only applies to non-null types. Its semantics are "assign later but stay non-null", while lateinit can achieve a similar effect, except that lateinit can only be used for class properties, not primitive types.
Local delegated properties
Delegation is not limited to class properties; local variables can be delegated too, a feature available since Kotlin 1.1.
Delegating a local variable to lazy gives you lazy loading, computing the value only when it is used.
Example
fun process
(
input
:
String
?
)
{
// Local variable delegated to lazy, computed on first access
val normalized
:
String
by lazy
{
println
(
"Normalizing"
)
input
?
.
trim
(
)
?
.
uppercase
(
)
?:
""
}
if
(
normalized.
isNotEmpty
(
)
)
{
// Initialization is triggered here
println
(
"Result: $normalized"
)
}
}
fun main
(
)
{
process
(
" runoob "
)
process
(
null
)
// This also triggers initialization, but the result is null so the result line is not printed
}
The output is:
执行规范化
结果:RUNOOB
执行规范化
If a branch never touches the variable, its initialization logic never runs at all, which is exactly the value of lazy loading.
provideDelegate
By default, the delegate object is created directly at the property declaration site.
If the object to the right of by defines provideDelegate, the compiler calls it instead to create the actual delegate instance, a feature available since Kotlin 1.1.
Its greatest value is that validation can happen at property-binding time rather than waiting until the getter or setter runs.
Example
import
kotlin.properties.ReadOnlyProperty
import
kotlin.reflect.KProperty
// Delegate provider: validate the property name when the property is bound
class
ValidatedDelegate
<
T
(
privateval value
:
T,
private
val allowedName
:
String
)
{
operator fun provideDelegate
(
thisRef
:
Any
?
,
prop
:
KProperty
<*>
)
:
ReadOnlyProperty
<
Any
?, T
{
// Validate immediately at property creation; fail right away if the name is wrong
require
(
prop.
name
==
allowedName
)
{
"The property name must be $allowedName, but it is ${prop.name}"
}
return
object
:
ReadOnlyProperty
<
Any
?, T
{
override fun getValue
(
thisRef
:
Any
?
, property
:
KProperty
<*>
)
:
T
=
value
}
}
}
class
MyUI
{
val name by ValidatedDelegate
(
"Runoob Tutorial"
,
"name"
)
}
fun main
(
)
{
println
(
MyUI
(
)
.
name
)
}
The output is:
Runoob Tutorial
If you get the property name wrong, the error surfaces immediately when the object is created instead of only when the property is read.
Example
import
kotlin.properties.ReadOnlyProperty
import
kotlin.reflect.KProperty
class
ValidatedDelegate
<
T
(
privateval value
:
T,
private
val allowedName
:
String
)
{
operator fun provideDelegate
(
thisRef
:
Any
?
,
prop
:
KProperty
<*>
)
:
ReadOnlyProperty
<
Any
?, T
{
require
(
prop.
name
==
allowedName
)
{
"The property name must be $allowedName, but it is ${prop.name}"
}
return
object
:
ReadOnlyProperty
<
Any
?, T
{
override fun getValue
(
thisRef
:
Any
?
, property
:
KProperty
<*>
)
:
T
=
value
}
}
}
class
MyUI
{
// The property name is siteName, which does not match allowedName, so constructing MyUI fails immediately
val siteName by ValidatedDelegate
(
"Runoob Tutorial"
,
"name"
)
}
The output is as follows (stack trace omitted):
Exception in thread "main" java.lang.IllegalArgumentException: 属性名必须是 name,实际是 siteName
provideDelegate takes the same parameters as getValue; it only affects creation of the backing property and does not change the generated getter and setter code.
Translation rules
Behind every delegated property, the compiler generates a hidden backing property and delegates the accessors to it.
For a property prop, the generated backing property is called prop$delegate.
Example
class
MyDelegate
{
operator fun getValue
(
thisRef
:
Any
?
, property
:
kotlin.
reflect
.
KProperty
<*>
)
:
String
=
"value"
operator fun setValue
(
thisRef
:
Any
?
, property
:
kotlin.
reflect
.
KProperty
<*>
, value
:
String
)
{
}
}
class
C
{
var prop
:
String
by MyDelegate
(
)
}
// The code above is roughly equivalent to what the compiler generates below:
class
CGenerated
{
private
val prop$delegate
=
MyDelegate
(
)
var prop
:
String
get
(
)
=
prop$delegate.
getValue
(
this
,
this
::
prop
)
set
(
value
:
String
)
=
prop$delegate.
setValue
(
this
,
this
::
prop, value
)
}
If provideDelegate is used, initialization of the backing property becomes a call to provideDelegate.
Example
import
kotlin.properties.ReadOnlyProperty
import
kotlin.reflect.KProperty
class
MyDelegate
{
// Once provideDelegate is defined, the compiler calls it to create the delegate object
operator fun provideDelegate
(
thisRef
:
Any
?
, prop
:
KProperty
<*>
)
:
ReadOnlyProperty
<
Any
?, String
{
println
(
"Binding property ${prop.name}"
)
return
object
:
ReadOnlyProperty
<
Any
?, String
{
override fun getValue
(
thisRef
:
Any
?
, property
:
KProperty
<*>
)
:
String
=
"value"
}
}
}
class
C
{
val prop
:
String
by MyDelegate
(
)
}
// When provideDelegate exists, the generated backing property becomes:
class
CGenerated
{
// Call provideDelegate to create the actual delegate object
private
val prop$delegate
=
MyDelegate
(
)
.
provideDelegate
(
this
,
this
::
prop
)
val prop
:
String
get
(
)
=
prop$delegate.
getValue
(
this
,
this
::
prop
)
}
Here this::prop is a KProperty reflection object carrying metadata such as the property's name, which is how the delegate knows which property it serves.
Common questions
Below are the most common problems encountered when using delegation.
| Problem | Reason | Solution |
|---|---|---|
| The delegate is missing the operator keyword | getValue / setValue must be declared as operator functions | Add operator before the methods |
| Trying to assign to a delegated val property | The delegate has no setValue, and a read-only property cannot be assigned anyway | Change the property to var and add setValue |
| An error occurs when reading from a Map delegate | The corresponding key is missing from the map | Make sure the key matches the property name, or use a map with default values |
| Delegates.notNull throws on read | The property was accessed before being assigned | Assign before reading, or switch to a nullable type |
| lazy initialization runs repeatedly under multithreading | The NONE mode is being used | Switch back to the default SYNCHRONIZED mode |
| Want to see what code delegation actually generates | The backing property is generated by the compiler and is not visible in the source | Decompile the bytecode and inspect the prop$delegate field |