Hanbit the Developer
Kotlin Documentation | Delegation 본문
Category: Concepts - Classes and objects
문서 링크: https://kotlinlang.org/docs/delegation.html
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 b = BaseImpl(10)
Derived(b).print()
}
BaseImpl에서 구현된 print()를 Derived에서 그대로 사용할 수 있다.(구현 내용을 다른 클래스에 위임함)
Overriding a member of an interface implemented by delegation
interface Base {
val message: String
fun print()
}
class BaseImpl(val 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 accessed from b's implementation of `print`
override val message = "Message of Derived"
}
fun main() {
val b = BaseImpl(10)
val derived = Derived(b)
derived.print()
println(derived.message)
}
BaseImpl: x = 10
Message of Derived
'Kotlin' 카테고리의 다른 글
Kotlin Documentation | Type aliases (0) | 2023.05.23 |
---|---|
Kotlin Documentation | Delegated properties (0) | 2023.05.23 |
Kotlin Documentation | Object expressions and declarations (0) | 2023.05.23 |
Kotlin Documentation | Inline classes (0) | 2023.05.23 |
Kotlin Documentation | Enum classes (0) | 2023.05.23 |