【发布时间】:2020-07-17 20:24:01
【问题描述】:
我真的对 kotlin 代表团感到困惑。让我在这里描述一下看起来像 kotlin 委托的常规多态方法。
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
fun main(args: Array<String>) {
val b : Base = BaseImpl(10)
b.print() // prints 10
}
我可以将Base接口的任何实现类传递给b变量来调用指定类对象的方法。那么kotlin的委托有什么好处呢?描述为here。
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b // why extra line of code?
// if the above example works fine without it.
fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).print() // prints 10
}
我知道这是两个代码都可以正常工作的简单场景。委托应该有一个好处,这就是 kotlin 引入它的原因。有什么区别?以及 kotlin 委托如何有用?请给我一个工作示例来与多态方法进行比较。
【问题讨论】:
-
我想知道这是不是更多关于委托本身的优点的问题,而不是关于 Kotlin 如何实现它的问题。
-
我问它知道 kotlin 委托有什么用?不是代表团如何有用。因为我已经知道代表团的目的。但是 kotlin 的实现让我很困惑。
-
第一段代码给出的结果与第二段不同。尝试手动实现
Derived,你会感觉到不同。 -
你能写出短代码吗?因为我真的不知道哪个例子可以区分它们。
-
有很多关于“组合与继承”主题的博客文章,例如。 G。 codingdelight.com/2014/01/16/… 或 thoughtworks.com/de/insights/blog/…
标签: kotlin