-
Notifications
You must be signed in to change notification settings - Fork 1
/
Delegation.kt
43 lines (35 loc) · 1.11 KB
/
Delegation.kt
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Delegation {
fun test() {
println("Implementation by delegation")
val baseImpl = BaseImpl(10)
Derived(baseImpl).println() // message from BaseImpl, if you want to show message from Derived, override println()
Derived(baseImpl).print()
println(Derived(baseImpl).message) // message from Derived
}
interface Base {
val message: String
fun print()
fun println()
}
class BaseImpl(x: Int) : Base {
override val message = "BaseImpl: x = $x"
override fun print() {
print(message)
}
override fun println() {
println(message)
}
}
// The last "b" (from ": Base by b") is implemented by the "b" in "Derived(b: Base)"
class Derived(b: Base) : Base by b {
override val message = "Message of Derived"
// overriding functions is optional
override fun print() {
print("Derived\n")
}
// override println() or println the message from BaseImpl
// override fun println() {
// println(message)
// }
}
}