What does `class C(val field: T): T by field` mean?

This is called delegation, specifically it is a type of delegation known as implementation by delegation.

By doing this, the class C implements the interface using the other object.

i.e. when you call the method (function) defined in the interface then the call is going to get transferred to the object you delegated in your case it is the field

interface T {
    fun print()
}
class TImpl: T {
    override fun print() = print("Hello World!")
}

class C(val field: T) : T by field {...}

fun main() {
    val c = C(TImpl())
    c.print()                 //Prints: Hello World!
}

Here the print() call gets transferred to TImpl because class C implements T by using field.


This syntax is a shortcut offered by the kotlin language to say that C implements T and delegates all T method implementations to the field member.

In Java or other OO languages, you would achieve the same by declaring each T method in C and calling field.theMethod in each of them (aka valueless boilerplate code)

Kotlin does that for you in the resulting Java bytecode it produces.

Tags:

Kotlin