我目前正在观看来自Google I / O 2017的此video,并且遇到了Kotlin的by
功能。
有以下示例可以避免在实际只关注其中一个方法时实现接口的每个方法。
by
实施(来自视频):
class MyListener : TransitionListener by EmptyTransitionListener {
override fun onTransitionStart(transition: Transition) {
}
}
object EmptyTransitionListener : TransitionListener {
override fun onTransitionEnd(transition: Transition) {}
override fun onTransitionResume(transition: Transition) {}
override fun onTransitionPause(transition: Transition) {}
override fun onTransitionCancel(transition: Transition) {}
override fun onTransitionStart(transition: Transition) {}
}
window.sharedElementEnterTransition.addListener(MyListener())
没有by
实施(我以前做过):
open class EmptyTransitionListener : TransitionListener {
override fun onTransitionEnd(transition: Transition) {}
override fun onTransitionResume(transition: Transition) {}
override fun onTransitionPause(transition: Transition) {}
override fun onTransitionCancel(transition: Transition) {}
override fun onTransitionStart(transition: Transition) {}
}
window.sharedElementEnterTransition.addListener(object: EmptyTransitionListener() {
override fun onTransitionStart(transition: Transition) {
}
})
一个优于另一个的优点是什么?
答案 0 :(得分:2)
它只遵循"Composition over inheritance"的原则。
面向对象编程(OOP)中的继承(或复合重用原则)的组合原则是类应该通过其组合实现多态行为和代码重用(通过包含实现所需功能的其他类的实例)而不是从基类或父类继承。这是OOP经常陈述的原则 [...]。
by
这正是by
的内容,是Kotlin应用class delegation的关键字。
委托模式已被证明是实现继承的一个很好的替代方案,而Kotlin本身就支持它需要零样板代码。
另请参阅https://en.wikipedia.org/wiki/Delegation_pattern:
在软件工程中,委托模式是一种面向对象的设计模式,它允许对象组合实现与继承相同的代码重用。 [...]
请按照stackoverflow discussion了解更多信息。
答案 1 :(得分:1)
使用by
,您可以重复使用多个类的相同实现。
class MyListener : TransitionListener by EmptyTransitionListener {
override fun onTransitionStart(transition: Transition) {
Log.d("MyListener", "Hi from MyListener!")
}
}
class MySecondListener : TransitionListener by EmptyTransitionListener {
override fun onTransitionStart(transition: Transition) {
Log.d("MySecondListener ", "Hi from MySecondListener!")
}
}
object EmptyTransitionListener : TransitionListener {
override fun onTransitionEnd(transition: Transition) {}
override fun onTransitionResume(transition: Transition) {}
override fun onTransitionPause(transition: Transition) {}
override fun onTransitionCancel(transition: Transition) {}
override fun onTransitionStart(transition: Transition) {}
}
window.sharedElementEnterTransition.addListener(MyListener())