android - 为什么在匿名子类上使用 Kotlin "by"?

标签 android kotlin kotlin-android-extensions

我正在看这个video来自 Google I/O 2017 并遇到了 Kotlin 的 by 功能。

下面的示例可以避免在您实际上只关心其中一个方法时实现接口(interface)的每个方法。

通过 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) {
            }
        })

一个比另一个有什么优势?

最佳答案

原则:组合 > 继承

简单的遵循"Composition over inheritance"的原则.

Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class. This is an often-stated principle of OOP [...].

Kotlin 委派 by

这正是 by 的意思,Kotlin 用于应用 class delegation 的关键字.

The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code.

委托(delegate)模式

另请参阅 https://en.wikipedia.org/wiki/Delegation_pattern :

In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance. [...]

进一步阅读

关注这个stackoverflow discussion更多信息。

关于android - 为什么在匿名子类上使用 Kotlin "by"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404028/

相关文章:

Android - imageView.getDrawable() 返回 null

android - 使用 Kotlin Android Extensions 以编程方式扩展布局

android - 无法减少 kotlin 中的 bool 值列表

android - 在 Kotlin 中使用 okhttp 信任 HTTPS 证书时出错

android - Android gradle androidDependencies实现,不仅使用此命令

java - SAX 的 characters() 方法未解析文本节点中的特殊字符

unit-testing - MockK 的 spyk 如何覆盖构造函数?

android - Kotlin - 检查泛型参数是否可选?

java - Docx4J(Android):如何在Word文档中读取页眉和页脚的内容

java - 如何显示图像的RGB值直方图?