Here is my test code:
class Test {
init {
a = 1
}
constructor() {
a = 2
}
private var a: Int
init {
a = 3
}
}
If I remove the secondary constructor:
class Test {
init {
a = 1 // Error: Variable cannot be initialized before declaration
}
// constructor() {
// a = 2
// }
private var a: Int
init {
a = 3
}
}
I know that
During an instance initialization, the initializer blocks are executed in the same order as they appear in the class body.
But why can I initialize the variable before its declaration if there is a secondary constructor?
Update:
And I found an interesting thing:
class Test {
init {
a = log(1)
}
constructor() {
a = log(2)
}
private var a: Int = log(0)
init {
a = log(3)
}
}
fun log(i: Int): Int {
println(i)
return i
}
fun main(args: Array<String>) {
Test()
}
The output is: 1 0 3 2, this is same as Java, declaration and initialization are two different step, but that is weird for Kotlin's primary constructor, Er...
1 0 3 2) is explained in the documentation (go to the section named Secondary Constructors).constructor()is a weird thing since it clashes with the primary constructor signature. Shouldn't it be a error?