Access constructor argument, not field

Hello,

consider this example:

abstract class A(open val x: Int, y: Int = x) {

    init {
        println("x:${x}, y:${y}")
    }
}

class B(override val x: Int) : A(42)

fun main(args: Array<String>) {
    B(42) // prints: x:0, y:42
}

The problem is that x accesses the field (this.x which is not set yet, because B is not initialized yet) not the constructor argument (which is defined). Is there a way to access “x the constructor argument” directly?
As in the above example you can create another parameter and make it default to the first, but this feels really awkward.

2 Likes

It looks odd but this seems to work:

abstract class A(x: Int) {
    open val x = x

    init {
        println("x:$x")
    }
}

class B(override val x: Int) : A(42)

fun main(args: Array<String>) {
    B(42)  // prints: x:42
}
1 Like

That’s really an improvement!
Thanks.