【发布时间】:2018-01-29 05:50:35
【问题描述】:
我该如何解决以下情况?
interface I
class A(i: I)
class C : I, A(this) // << --- 'this' is not defined in this context
简而言之,我想将类实例传递给超类构造函数。
在 Kotlin 中可以吗?
附言 所有的答案都是好的并且在技术上是正确的。但是让我们举一个具体的例子:
interface Pilot {
fun informAboutObstacle()
}
abstract class Car(private val pilot: Pilot) {
fun drive() {
while (true) {
// ....
if (haveObstacleDetected()) {
pilot.informAboutObstacle()
}
// ....
}
}
fun break() {
// stop the car
}
}
class AutopilotCar : Pilot, Car(this) { // For example, Tesla :)
override fun informAboutObstacle() {
break() // stop the car
}
}
这个例子看起来不太做作,为什么我不能用OOP友好的语言来实现呢?
【问题讨论】:
-
这可能比继承更适合组合。让您的
C维护I的实例,而不是成为 一个。或者,您可以允许A类通过 setter 提供其I,而不是在初始化时提供。 -
如果它必须是继承,您可以使用辅助零参数构造函数并检查它是否实现了 I?
-
我认为您的扩展示例并没有为问题陈述添加任何实质性内容。你仍然有这个不方便的事实,你让
Car引用自己,就好像它是另一个合作者对象一样。我认为将Autopilot建模为Pilot和Car没有任何好处。
标签: kotlin