Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' is not defined in this context

Tags:

kotlin

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 the class instance to super class constructor.
Is it possible in Kotlin?

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
    }
}

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

like image 442
Alexey Avatar asked Jan 25 '18 20:01

Alexey


1 Answers

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

From

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.

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 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.

like image 70
Ingo Kegel Avatar answered Sep 19 '22 06:09

Ingo Kegel