在此上下文中未定义"this" [英] 'this' is not defined in this context

查看:106
本文介绍了在此上下文中未定义"this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解决以下情况?

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

简而言之,我想将类实例传递给超类构造函数.
在科特林有可能吗?

In short, I want to pass the class instance to super class constructor.
Is it possible in Kotlin?

PS 所有答案都是正确的,并且在技术上是正确的.但让我们举一个具体的例子:

P.S. All the answers are good and technically correct. But let's give a concrete example:

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友好的语言来实现它?

This example don't look too contrived, and why can't I implement it with OOP-friendly language?

推荐答案

否,这在JVM上是不可能的. this仅在初始化超类之后可用.

No, this is not possible on the JVM. this is only available after the super class has been initialized.

来自

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

类myClass的实例初始化方法(第2.9.1节)将新的未初始化对象视为其在局部变量0中的this参数.在该方法调用此实例上的myClass或其直接超类的另一个实例初始化方法之前,唯一的操作该方法可以执行的工作是分配在myClass中声明的字段.

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.

因此,在调用超类构造函数之前,禁止将字节码指令aload 0压入堆栈.这就是为什么不能将其作为参数传递给超级构造函数的原因.

So the bytecode instruction aload 0 to push this on the stack is forbidden before the super-class constructor is called. That's why it cannot be passed as an argument to the super-constructor.

Kotlin诞生于JVM语言,其目标是与Java代码实现最大的互操作性,并使其语言功能的开销降至最低.尽管Kotlin可以选择以其他方式协调对象初始化,但会在Java-Kotlin混合类层次结构中产生问题,并增加大量开销.

Kotlin was born as a JVM language and aims for maximum interoperability with Java code and a minimum overhead of its language features. While Kotlin could have chosen to orchestrate object initialization in a different way, it would create problems in mixed Java-Kotlin class hierarchies and add significant overhead.

这篇关于在此上下文中未定义"this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆