0Pricing
Kotlin Academy · Lesson

Delegating to Members

Compose behavior.

Composing Behavior

Real objects often need to combine several capabilities. Instead of inheriting from many sources, you can delegate each capability to a dedicated member object.

Two Roles, One Class

Suppose a class should both read and write. Define two interfaces and delegate each to its own implementation.

interface Reader { fun read(): String }
interface Writer { fun write(s: String): String }

class FileReader : Reader { override fun read() = "contents" }
class FileWriter : Writer { override fun write(s: String) = "wrote " + s }

class FileIO(r: Reader, w: Writer) : Reader by r, Writer by w

fun main() {
    val io = FileIO(FileReader(), FileWriter())
    println(io.read())
    println(io.write("data"))
}

All lessons in this course

  1. The by Keyword
  2. Delegating to Members
  3. Delegation vs Inheritance
  4. Practical Patterns
← Back to Kotlin Academy