0

I do not understand why in this code values of i and s are 0 and null respectively in init{} block but in second constructor of class B these values are 200 and param2?

class A(override var i: Int, override var s: String) : B(200, "param2","param3") {
        init {
           println(i)
           println(s)
        }
 }



open class B(open var i: Int, open var s: String) {
    init {
        println("class B init")
        println("i in init B2 is $i")
        println("s in init B2 is $s")
    }


   constructor(i: Int, s: String, s2: String) : this(i, s) {
        println("second constructor B")
        println(" i = $i in second constructor")
        println(" s = $s in second constructor")
        println(" s2 = $s2 in second constructor")
    }

}

    
fun main() {
   val ins2 = A(500, "500S") 
}

results:

    class B init
    i in init B2 is 0
    s in init B2 is null
    second constructor B
    i = 200 in second constructor
    s = param2 in second constructor
    s2 = param3 in second constructor
    500
    500S

I need some explication please.

Tarmo
  • 3,851
  • 2
  • 24
  • 41

1 Answers1

1

You have 2 warnings in that code, both Accessing non-final property X in constructor (one for i and one for s). Have a read here Kotlin calling non final function in constructor works.

That is the reason you get 0 and null first.

The reason you then get 200 and param2 is because that is what you tell it to do here B(200, "param2","param3").

You aren't creating it with the values from A, you are calling that constructor with those predefined values.

And afterwards, those values are overwritten by the i and s inside A.

AlexT
  • 2,524
  • 1
  • 11
  • 23