Allow access to initialized class fields during construction


#1
class Foo(val bar: Boolean,
      val conditional: Int = if(bar) 1 else 2)

// works fine
fun test() {
    val f = Foo(true)
}

// will not compile  - unresolved reference 'bar'
fun test2() {
    val f2 = Foo(bar = true, if(bar) 1 else 2)
}

// ugly workaround
fun test3() {
     val bar = true
     val f3 = Foo(bar,  if(bar) 1 else 2)
}

Kotlin allows initializing fields with default values which can be based on previously initialized ones, but when you need to calculate property value in the runtime you need an external local variable. So I suggest to add ability to access initialized properties during construction. This example is synthetic but I often need this when data received from network and in protocol conditional read or skip for property value.


#2

Adding this feature would add a huge set of complications to how scoping rules work in Kotlin. Just as a simple example, we’d need to add special syntax to allow you to distinguish between local variables and class properties if they have the same name.

I’m completely sure that, if your code currently looks ugly, it’s possible to restructure it in a non-ugly way without adding any new features to Kotlin.