Kotlin委托

Posted on 2024-11-11 17:23  Capterlliar  阅读(15)  评论(0编辑  收藏  举报

问就是上班真碰见了,感觉是考试会喜欢出的题

委托,写作 A by B,当A和B均为class时,意为把A的部分交给B处理,也可以理解为A使用 B中和A相关 的部分,因此B中一定要有A需要的部分,A是B的子集。

也可以是属性委托,var p: String by Delegate(),其中Delegate实现getValue和setValue。

请看以下均为合法的委托:

interface Store {
    fun store()
}

interface Cat {
    fun cat()
}

class Home : Store, Cat {
    override fun store() {}

    override fun cat() {}
}

open class DelegateStore(s: Home) : Store by s

open class DelegateCat(s: Home) : Cat by s

class Foo2(s: Home) : Cat by s

class Foo3(s: Home) : DelegateStore(s), Store

class Foo4(s: Home) : DelegateStore(s), Cat {
    override fun cat() {}
}

其中Foo4中,虽然s类型为Home,同时继承了Cat和Store(名字我乱起的不要在意),但它继承的是DelegateStore,因此编译器只能看见Home中Store的部分,如果你想要Cat,需要override一下fun cat()

但Foo3就没有这个问题了~