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
TrailLogimplementsLoggerthe ordinary way.class GuidedTrip(logbook: Logger) : Logger by logbookwrites the forwarding for you.- The class adds
departon top and still answers everyLoggercall.
Keywords and builtins used here
GuidedTripLoggerStringTrailLogbyclassdepartfuninterfacelogmainoverrideval
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.
Step 2 of 3 in Generics & delegation, step 23 of 27 in Language basics.