Делегирование
Паттерн делегирования зарекомендовал себя как хорошая альтернатива наследованию реализации, а Kotlin поддерживает его изначально, не требуя шаблонного кода.
Класс Derived может реализовать интерфейс Base, делегируя все свои открытые члены указанному объекту:
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
fun main() {
val base = BaseImpl(10)
val derived = Derived(base)
derived.print()
// 10
}
Оператор by в списке суперклассов для Derived указывает, что b будет храниться внутри объектов Derived, а компилятор сгенерирует все методы Base, перенаправляющие вызовы к b.
Переопределение члена интерфейса, реализованного с помощью делегирования
Переопределения работают так, как и ожидается: компилятор будет использовать ваши реализации override вместо реализаций объекта-делегата. Если вы хотите добавить override fun printMessage() { print("abc") } к Derived, программа выведет abc вместо 10 при вызове printMessage:
interface Base {
fun printMessage()
fun printMessageLine()
}
class BaseImpl(val x: Int) : Base {
override fun printMessage() { print(x) }
override fun printMessageLine() { println(x) }
}
class Derived(b: Base) : Base by b {
override fun printMessage() { println("abc") }
}
fun main() {
val base = BaseImpl(10)
val derived = Derived(base)
derived.printMessage()
// abc
derived.printMessageLine()
// 10
}
Однако обратите внимание, что члены, переопределённые таким образом, не вызываются из членов объекта-делегата, который может обращаться только к собственным реализациям членов интерфейса:
interface Base {
val message: String
fun print()
}
class BaseImpl(x: Int) : Base {
override val message = "BaseImpl: x = $x"
override fun print() { println(message) }
}
class Derived(b: Base) : Base by b {
// This property is not accessible
// from b's implementation of `print()`
override val message = "Message of Derived"
}
fun main() {
val base = BaseImpl(10)
val derived = Derived(base)
derived.print()
// BaseImpl: x = 10
println(derived.message)
// Message of Derived
}
Подробнее о делегированных свойствах.
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/delegation.html