Koltin inner class extends inner class in outer class with parallel hierarchies but give Unhandled JavaScript exception

Viewed 21
class QualifiedCalls {
  var name = "QualifiedCalls"

  open inner class Outer1 {
    open var name = "Outer1"

    open inner class Inner1 {
      open var name = "Inner1"
      var superResult: String

      constructor() {
        this.superResult = this.name + this@Outer1.name + this@QualifiedCalls.name
      }
    }
  }

    inner class Outer2 : Outer1() {
    override var name = "Outer2"

    inner class Inner2 : Inner1 {
      override var name = "Inner2"
      var result: String 

      constructor() : super() {
          

        result = this@Outer2.name + this@QualifiedCalls.name + superResult
      }
    }
  }
}

fun main() {
    val test = QualifiedCalls().Outer2().Inner2()
  // In java test.result is "Inner2Outer2QualifiedCallsInner1Outer1QualifiedCalls"
    println(test.result)
}

I expected this to print "Inner2Outer2QualifiedCallsInner1Outer1QualifiedCalls", however, it gives the following error

Unhandled JavaScript exception: Cannot read properties of undefined (reading 'name') 
 TypeError: Cannot read properties of undefined (reading 'name')
    at QualifiedCalls$Outer1$QualifiedCalls$Outer1$Inner1_init (eval at  (https://play.kotlinlang.org/main.js:2:2074837), :51:66)
    at QualifiedCalls$Outer2$QualifiedCalls$Outer2$Inner2_init (eval at  (https://play.kotlinlang.org/main.js:2:2074837), :94:5)

If I write like following:

inner class Outer2 : Outer1() {
    override var name = "Outer2"

    inner class Inner2() : Inner1() {
      override var name = "Inner2"
      var result: String

      init {
          

        result = this@Outer2.name + this@QualifiedCalls.name + superResult
      }
    }
  }

Then the test result will be Outer2QualifiedCallsundefinedOuter2QualifiedCalls, why the result is this? From my understanding Code in initializer blocks effectively becomes part of the primary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks and property initializers is executed before the body of the secondary constructor. Thanks

0 Answers
Related