我真的很困惑kotlin代表团。让我来描述这里的规则多态性方法,它看起来像kotlin delgation一样。科特林代表团如何有用?
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的实施让我感到困惑。 – UnKnown
第一个代码块没有给出与第二个相同的结果。试着手工实现'派生',你会感受到不同。 – Ilya