Hanbit the Developer

Kotlin Documentation | Delegation 본문

Mobile/Kotlin

Kotlin Documentation | Delegation

hanbikan 2023. 5. 23. 16:21

Kotlin Documentation 시리즈에 대해

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