Delegated Properties

There are certain common kinds of properties, that, though we can implement them manually every time we need them, would be very nice to implement once and for all, and put into a library. Examples include:

  • lazy properties: the value gets computed only upon first access;
  • observable properties: listeners get notified about changes to this property;
  • storing properties in a map, instead of a separate field for each property.

To cover these (and other) cases, Kotlin supports delegated properties:

  1. class Example {
  2. var p: String by Delegate()
  3. }

The syntax is: val/var <property name>: <Type> by <expression>. The expression after by is the delegate, because get() (and set()) corresponding to the property will be delegated to its getValue() and setValue() methods. Property delegates don’t have to implement any interface, but they have to provide a getValue() function (and setValue() — for vars). For example:

  1. import kotlin.reflect.KProperty
  2. class Delegate {
  3. operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
  4. return "$thisRef, thank you for delegating '${property.name}' to me!"
  5. }
  6. operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
  7. println("$value has been assigned to '${property.name}' in $thisRef.")
  8. }
  9. }

When we read from p that delegates to an instance of Delegate, the getValue() function from Delegate is called, so that its first parameter is the object we read p from and the second parameter holds a description of p itself (e.g. you can take its name). For example:

  1. val e = Example()
  2. println(e.p)

This prints:

  1. Example@33a17727, thank you for delegating p to me!

Similarly, when we assign to p, the setValue() function is called. The first two parameters are the same, and the third holds the value being assigned:

  1. e.p = "NEW"

This prints

  1. NEW has been assigned to p in Example@33a17727.

The specification of the requirements to the delegated object can be found below.

Note that since Kotlin 1.1 you can declare a delegated property inside a function or code block, it shouldn’t necessarily be a member of a class. Below you can find an example.

Standard delegates

The Kotlin standard library provides factory methods for several useful kinds of delegates.

Lazy

lazy() is a function that takes a lambda and returns an instance of Lazy<T> which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.

  1. val lazyValue: String by lazy {
  2. println("computed!")
  3. "Hello"
  4. }
  5. fun main() {
  6. println(lazyValue)
  7. println(lazyValue)
  8. }

By default, the evaluation of lazy properties is synchronized: the value is computed only in one thread, and all threads will see the same value. If the synchronization of initialization delegate is not required, so that multiple threads can execute it simultaneously, pass LazyThreadSafetyMode.PUBLICATION as a parameter to the lazy() function. And if you’re sure that the initialization will always happen on the same thread as the one where you use the property, you can use LazyThreadSafetyMode.NONE: it doesn’t incur any thread-safety guarantees and the related overhead.

Observable

Delegates.observable() takes two arguments: the initial value and a handler for modifications. The handler is called every time we assign to the property (after the assignment has been performed). It has three parameters: a property being assigned to, the old value and the new one:

  1. import kotlin.properties.Delegates
  2. class User {
  3. var name: String by Delegates.observable("<no name>") {
  4. prop, old, new ->
  5. println("$old -> $new")
  6. }
  7. }
  8. fun main() {
  9. val user = User()
  10. user.name = "first"
  11. user.name = "second"
  12. }

If you want to intercept assignments and “veto” them, use vetoable() instead of observable(). The handler passed to the vetoable is called before the assignment of a new property value has been performed.

Delegating to another property

Since Kotlin 1.4, a property can delegate its getter and setter to another property. Such delegation is available for both top-level and class properties (member and extension). The delegate property can be:

  • a top-level property
  • a member or an extension property of the same class
  • a member or an extension property of another class

To delegate a property to another property, use the proper :: qualifier in the delegate name, for example, this::delegate or MyClass::delegate.

  1. var topLevelInt: Int = 0
  2. class ClassWithDelegate(val anotherClassInt: Int)
  3. //sampleStart
  4. class MyClass(var memberInt: Int, val anotherClassInstance: ClassWithDelegate) {
  5. var delegatedToMember: Int by this::memberInt
  6. var delegatedToTopLevel: Int by ::topLevelInt
  7. val delegatedToAnotherClass: Int by anotherClassInstance::anotherClassInt
  8. }
  9. var MyClass.extDelegated: Int by ::topLevelInt
  10. //sampleEnd

This may be useful, for example, when you want to rename a property in a backward-compatible way: you introduce a new property, annotate the old one with the @Deprecated annotation, and delegate its implementation.

  1. class MyClass {
  2. var newName: Int = 0
  3. @Deprecated("Use 'newName' instead", ReplaceWith("newName"))
  4. var oldName: Int by this::newName
  5. }
  6. fun main() {
  7. val myClass = MyClass()
  8. // Notification: 'oldName: Int' is deprecated.
  9. // Use 'newName' instead
  10. myClass.oldName = 42
  11. println(myClass.newName) // 42
  12. }

Storing properties in a map

One common use case is storing the values of properties in a map. This comes up often in applications like parsing JSON or doing other “dynamic” things. In this case, you can use the map instance itself as the delegate for a delegated property.

  1. class User(val map: Map<String, Any?>) {
  2. val name: String by map
  3. val age: Int by map
  4. }

In this example, the constructor takes a map:

  1. val user = User(mapOf(
  2. "name" to "John Doe",
  3. "age" to 25
  4. ))

Delegated properties take values from this map (by the string keys –– names of properties):

  1. class User(val map: Map<String, Any?>) {
  2. val name: String by map
  3. val age: Int by map
  4. }
  5. fun main() {
  6. val user = User(mapOf(
  7. "name" to "John Doe",
  8. "age" to 25
  9. ))
  10. //sampleStart
  11. println(user.name) // Prints "John Doe"
  12. println(user.age) // Prints 25
  13. //sampleEnd
  14. }

This works also for var’s properties if you use a MutableMap instead of read-only Map:

  1. class MutableUser(val map: MutableMap<String, Any?>) {
  2. var name: String by map
  3. var age: Int by map
  4. }

Local delegated properties

You can declare local variables as delegated properties. For instance, you can make a local variable lazy:

  1. fun example(computeFoo: () -> Foo) {
  2. val memoizedFoo by lazy(computeFoo)
  3. if (someCondition && memoizedFoo.isValid()) {
  4. memoizedFoo.doSomething()
  5. }
  6. }

The memoizedFoo variable will be computed on the first access only. If someCondition fails, the variable won’t be computed at all.

Property delegate requirements

Here we summarize requirements to delegate objects.

For a read-only property (val), a delegate has to provide an operator function getValue() with the following parameters:

  • thisRef — must be the same or a supertype of the property owner (for extension properties — the type being extended).
  • property — must be of type KProperty<*> or its supertype.

getValue() must return the same type as the property (or its subtype).

  1. class Resource
  2. class Owner {
  3. val valResource: Resource by ResourceDelegate()
  4. }
  5. class ResourceDelegate {
  6. operator fun getValue(thisRef: Owner, property: KProperty<*>): Resource {
  7. return Resource()
  8. }
  9. }

For a mutable property (var), a delegate has to additionally provide an operator function setValue() with the following parameters:

  • thisRef — must be the same or a supertype of the property owner (for extension properties — the type being extended).
  • property — must be of type KProperty<*> or its supertype.
  • value — must be of the same type as the property (or its supertype).
  1. class Resource
  2. class Owner {
  3. var varResource: Resource by ResourceDelegate()
  4. }
  5. class ResourceDelegate(private var resource: Resource = Resource()) {
  6. operator fun getValue(thisRef: Owner, property: KProperty<*>): Resource {
  7. return resource
  8. }
  9. operator fun setValue(thisRef: Owner, property: KProperty<*>, value: Any?) {
  10. if (value is Resource) {
  11. resource = value
  12. }
  13. }
  14. }

getValue() and/or setValue() functions may be provided either as member functions of the delegate class or extension functions. The latter is handy when you need to delegate property to an object which doesn’t originally provide these functions. Both of the functions need to be marked with the operator keyword.

You can create delegates as anonymous objects without creating new classes using the interfaces ReadOnlyProperty and ReadWriteProperty from the Kotlin standard library. They provide the required methods: getValue() is declared in ReadOnlyProperty; ReadWriteProperty extends it and adds setValue(). Thus, you can pass a ReadWriteProperty whenever a ReadOnlyProperty is expected.

  1. fun resourceDelegate(): ReadWriteProperty<Any?, Int> =
  2. object : ReadWriteProperty<Any?, Int> {
  3. var curValue = 0
  4. override fun getValue(thisRef: Any?, property: KProperty<*>): Int = curValue
  5. override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
  6. curValue = value
  7. }
  8. }
  9. val readOnly: Int by resourceDelegate() // ReadWriteProperty as val
  10. var readWrite: Int by resourceDelegate()

Translation rules

Under the hood, for every delegated property the Kotlin compiler generates an auxiliary property and delegates to it. For instance, for the property prop the hidden property prop$delegate is generated, and the code of the accessors simply delegates to this additional property:

  1. class C {
  2. var prop: Type by MyDelegate()
  3. }
  4. // this code is generated by the compiler instead:
  5. class C {
  6. private val prop$delegate = MyDelegate()
  7. var prop: Type
  8. get() = prop$delegate.getValue(this, this::prop)
  9. set(value: Type) = prop$delegate.setValue(this, this::prop, value)
  10. }

The Kotlin compiler provides all the necessary information about prop in the arguments: the first argument this refers to an instance of the outer class C and this::prop is a reflection object of the KProperty type describing prop itself.

Note that the syntax this::prop to refer a bound callable reference in the code directly has only been available since Kotlin 1.1.

Providing a delegate

By defining the provideDelegate operator you can extend the logic of creating the object to which the property implementation is delegated. If the object used on the right-hand side of by defines provideDelegate as a member or extension function, that function will be called to create the property delegate instance.

One of the possible use cases of provideDelegate is to check the consistency of the property upon its initialization.

For example, if you want to check the property name before binding, you can write something like this:

  1. class ResourceDelegate<T> : ReadOnlyProperty<MyUI, T> {
  2. override fun getValue(thisRef: MyUI, property: KProperty<*>): T { ... }
  3. }
  4. class ResourceLoader<T>(id: ResourceID<T>) {
  5. operator fun provideDelegate(
  6. thisRef: MyUI,
  7. prop: KProperty<*>
  8. ): ReadOnlyProperty<MyUI, T> {
  9. checkProperty(thisRef, prop.name)
  10. // create delegate
  11. return ResourceDelegate()
  12. }
  13. private fun checkProperty(thisRef: MyUI, name: String) { ... }
  14. }
  15. class MyUI {
  16. fun <T> bindResource(id: ResourceID<T>): ResourceLoader<T> { ... }
  17. val image by bindResource(ResourceID.image_id)
  18. val text by bindResource(ResourceID.text_id)
  19. }

The parameters of provideDelegate are the same as for getValue:

  • thisRef — must be the same or a supertype of the property owner (for extension properties — the type being extended);
  • property — must be of type KProperty<*> or its supertype.

The provideDelegate method is called for each property during the creation of the MyUI instance, and it performs the necessary validation right away.

Without this ability to intercept the binding between the property and its delegate, to achieve the same functionality you’d have to pass the property name explicitly, which isn’t very convenient:

  1. // Checking the property name without "provideDelegate" functionality
  2. class MyUI {
  3. val image by bindResource(ResourceID.image_id, "image")
  4. val text by bindResource(ResourceID.text_id, "text")
  5. }
  6. fun <T> MyUI.bindResource(
  7. id: ResourceID<T>,
  8. propertyName: String
  9. ): ReadOnlyProperty<MyUI, T> {
  10. checkProperty(this, propertyName)
  11. // create delegate
  12. }

In the generated code, the provideDelegate method is called to initialize the auxiliary prop$delegate property. Compare the generated code for the property declaration val prop: Type by MyDelegate() with the generated code above (when the provideDelegate method is not present):

  1. class C {
  2. var prop: Type by MyDelegate()
  3. }
  4. // this code is generated by the compiler
  5. // when the 'provideDelegate' function is available:
  6. class C {
  7. // calling "provideDelegate" to create the additional "delegate" property
  8. private val prop$delegate = MyDelegate().provideDelegate(this, this::prop)
  9. var prop: Type
  10. get() = prop$delegate.getValue(this, this::prop)
  11. set(value: Type) = prop$delegate.setValue(this, this::prop, value)
  12. }

Note that the provideDelegate method affects only the creation of the auxiliary property and doesn’t affect the code generated for getter or setter.

With the PropertyDelegateProvider interface from the standard library, you can create delegate providers without creating new classes.

  1. val provider = PropertyDelegateProvider { thisRef: Any?, property ->
  2. ReadOnlyProperty<Any?, Int> {_, property -> 42 }
  3. }
  4. val delegate: Int by provider