5.8.5 委托

原文链接: https://kotlinlang.org/docs/delegation.html

5.8.5 委托

委托模式已被证明是实现继承的一个良好替代方案,Kotlin 原生支持它,且无需任何样板代码。

类 Derived 可以把其所有公开成员委托给一个指定的对象,从而实现对接口 Base 的实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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
}

Derived 超类型列表中的 by 子句表示 b 会被保存在 Derived 对象的内部,编译器会生成 Base 的所有方法并转发给 b。

重写通过委托实现的接口成员

重写的行为与预期一致:编译器会使用你的 override 实现,而不是委托对象中的实现。如果你想给 Derived 添加 override fun printMessage() { print("abc") },那么在调用 printMessage 时程序会打印 abc 而不是 10:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
}

但请注意,以这种方式重写的成员不会被委托对象的成员调用,委托对象只能访问它自己对接口成员的实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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 {
    // 这个属性无法
    // 从 b 的 `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
}

更多内容请参阅委托属性。