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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But it means i cant access i or s in init block? or how can i do that?
0

I found out, strangely enough, that placing the property before the init block worked.

var thing = "" init { if (thing.isEmpty()) thing = "something" // this will now work } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.