by
키워드를 사용하여 쉽게 구현 가능by
키워드를 사용하여 쉽게 구현 가능interface Base {
fun say()
}
class BaseImpl(private val x: Int) : Base {
override fun say() {
println(x.toString())
}
}
class Derived(private val b: BaseImpl) : Base {
override fun say() {
b.say()
}
}
class Derived2 : Base by BaseImpl(10)
fun main() {
val b = BaseImpl(10)
Derived(b).say() // print: 10
Derived2().say() // print: 10
}
interface Base {
fun say()
}
class BaseImpl(private val x: Int) : Base {
override fun say() {
println(x.toString())
}
}
class Derived(private val b: BaseImpl) : Base {
override fun say() {
b.say()
}
}
class Derived2(baseImpl: Base) : Base by baseImpl
fun main() {
Derived2(BaseImpl(10)).say() // print: 10
Derived2(Derived(10)).say() // print: 10
}
interface Showable {
fun show()
}
interface Viewable{
fun view()
}
class Show: Showable {
override fun show() {
println("Show-show()")
}
}
class View: Viewable {
override fun view() {
println("View-view()")
}
}
class Screen (
val showable: Showable, val viewable : Viewable
): Showable by showable, Viewable by viewable
fun main() {
val show = Show()
val view = View()
Screen(show, view).show() // print: Show-show()
Screen(show, view).view() // print: View-view()
}
속성을 위임을 처리하는 메서드에는 notNull
observable
vetoable
가 있다.
notNull
: 클래스 멤버인 속성의 지연 초기화
import kotlin.properties.Delegates
...
lateinit var str: String
fun main() {
var str1: String by Delegates.notNull<String>()
var int1: Int by Delegates.notNull<Int>()
str = "Hello"
str1 = "World"
int1 = 10
}
observable
: 속성 변경 관찰
import kotlin.properties.Delegates
...
fun main() {
var observed = false
var max: Int by Delegates.observable(0) { _, old, new ->
println("Old value: $old,New value: $new")
observed = true // 변경 상태 변경
}
println("max: $max") // max: 0
println("observed: $observed") // observed: false
max = 10 // print: Old value: 0,New value: 10
println("max: $max") // max: 10
println("observed: $observed") // observed: true
}
vetoable
: 특정 조건이 일치할 때만 속성 위임 변경
import kotlin.properties.Delegates
...
fun main() {
var vetoableField: Int by Delegates.vetoable(0) { property, oldValue, newValue ->
println("vetoableField: $oldValue -> $newValue")
newValue >= 0
}
println(vetoableField) // 0
vetoableField = 1 //print: vetoableField: 0 -> 1
println(vetoableField) // 1
vetoableField = -1 //print: vetoableField: 1 -> -1
println(vetoableField) // 1
}