typestar

Delegation with by in Kotlin

Forward a whole interface to a wrapped instance in one clause.

interface Logger {
    fun log(line: String)
}

class TrailLog : Logger {
    override fun log(line: String) = println("[log] $line")
}

// by hands every Logger call to the wrapped instance -- no boilerplate.
class GuidedTrip(logbook: Logger) : Logger by logbook {
    fun depart(trail: String) = log("Departing $trail")
}

fun main() {
    val trip = GuidedTrip(TrailLog())
    trip.depart("Ridgeline")
    trip.log("All hikers accounted for")
}

How it works

  1. TrailLog implements Logger the ordinary way.
  2. class GuidedTrip(logbook: Logger) : Logger by logbook writes the forwarding for you.
  3. The class adds depart on top and still answers every Logger call.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
423
Tokens
95
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 2 of 3 in Generics & delegation, step 23 of 27 in Language basics.

← Previous Next →