'this' is not defined in this context

How can I solve the following case?

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

In short, I want to pass an instance of a class to a superclassic class.
Is this possible in Kotlin?

PS All answers are good and technically correct. But 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
    }
}

This example does not look too far-fetched, and why can't I implement it using an OOP-friendly language?

+4
source share
2 answers

No, this is not possible in the JVM. thisavailable only after initialization of the superclass.

WITH

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

(§2.9.1) myClass 0. myClass , , myClass.

, - aload 0, this , . -.

Kotlin JVM Java- . -, Java-Kotlin .

+6

, Java, # Swift, Kotlin this , . , , .

, , , A - , . this, , . , , , - , i.toString(). , . toString() , val s.

, , . A :

A and i

:

C is i

A - I. . . , C.toString() super.toString() A.toString() (A super of C), i.toString(), StackOverflowError.

, A , C : A , A I.

+2

Source: https://habr.com/ru/post/1692734/


All Articles