gpt4 book ai didi

kotlin - 'this' 未在此上下文中定义

转载 作者:IT老高 更新时间:2023-10-28 13:47:21 25 4
gpt4 key购买 nike

我该如何解决以下情况?

interface I
class A(i: I)
class C : I, A(this) // << --- 'this' is not defined in this context

简而言之,我想将类实例传递给父类(super class)构造函数。
在 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友好的语言来实现呢?

最佳答案

不,这在 JVM 上是不可能的。 this 仅在父类(super class)初始化后可用。

来自

https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.10.2.4

The instance initialization method (§2.9.1) for class myClass sees the new uninitialized object as its this argument in local variable 0. Before that method invokes another instance initialization method of myClass or its direct superclass on this, the only operation the method can perform on this is assigning fields declared within myClass.

所以在调用父类(super class)构造函数之前,禁止使用字节码指令aload 0this 压入堆栈。这就是为什么它不能作为参数传递给 super 构造函数的原因。

Kotlin 是作为一种 JVM 语言诞生的,旨在最大限度地实现与 Java 代码的互操作性,并将其语言特性的开销降至最低。虽然 Kotlin 可以选择以不同的方式编排对象初始化,但它会在混合 Java-Kotlin 类层次结构中产生问题并增加大量开销。

关于kotlin - 'this' 未在此上下文中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com