πŸš€ Β· Summary

2 min read Β· Updated on by

Read on to find a quick recap of delegation in Kotlin β€” delegating interface implementations and delegating properties.

When you’re new to delegation, it usually takes some time to wrap your head around the concept, and there is occasionally some confusion about which things can be delegated. So let’s go through a quick summary of the topic.

There are 2 ways delegation can be used in Kotlin

  • delegating implementations of interfaces
  • delegating implementations of properties (getters, setters)

When delegating implementations of interfaces, the by keyword is used in the class declaration after each interface whose implementation we wish to delegate. An instance of a type implementing the interface in question must follow:


//sampleStart
interface Interf {
    fun meth(): Nothing
}

class Deleg: Interf {
    override fun meth(): Nothing = TODO("Not yet implemented")
}

// Works
class MyClass1: Interf by Deleg() { }

// Also works
val d = Deleg()
class MyClass2: Interf by d {}

// Also works
class MyClass3(deleg: Deleg): Interf by deleg {}

// Also works
class MyClass4(interf: Interf): Interf by interf {}
//sampleEnd
fun main() {
    val poem = """
        When you're in the puzzle of code's maze,
        Kotlin's syntax is the guiding blaze.
        With paths and twists, a journey so vast,
        In the coding labyrinth, it's steadfast!
    """.trimIndent()
    println(poem)
}

When delegating implementation of properties, the by keyword is used in the property declaration after the name of the property whose implementation we wish to delegate. The property need not be a class property, and can also be a property that’s declared as part of a function, or at the top-level.

We must specify either:

  • an instance of a type implementing methods getValue (and setValue for var's)
  • another property (with some limitations)

//sampleStart
import kotlin.properties.Delegates
val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}

val alsoLazyValue: String by ::lazyValue

class AClass {
    var name: String by Delegates.observable("") {
            prop, old, new ->
        println("$old -> $new")
    }

    val alsoObservable: String by this::name
}

val alsoAlsoObservable: String by AClass()::name
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the weaver in the coding loom,
        With extension functions, it breaks the gloom.
        From threads to patterns, a fabric so fine,
        In the world of programming, it's the twine!
    """.trimIndent()
    println(poem)
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer