https://kotlinlang.org logo
Title
k

karelpeeters

10/08/2018, 9:04 AM
Of course the constructors of classes should be able to access
this
, and default parameters are evaluated in a constructor.
p

Pavlo Liapota

10/08/2018, 9:12 AM
class Person(val name: String) {
    constructor() : this(this.fun1())
    
    fun fun1() = ""
}
Gives:
Cannot access '<this>' before superclass constructor has been called
🙂
e

Egor Trutenko

10/08/2018, 9:16 AM
This is not the same. It is purely linking outer source to the inner state, this is what Kotlin's feature of defining properties in the very constructor is for. But imagine the following:
class StateSensitive(
  val someVal: Int = this.getState()
) {

  private val state = 2

  fun getState() = state
}
It's quite rough, but speaks for situation pretty much.
state
will be initialized after the resolution of
someVal
, so you can't access it, but still do.
k

karelpeeters

10/08/2018, 9:17 AM
There is no "outer" at all, default parameter are evaluated in the class.
e

Egor Trutenko

10/08/2018, 9:18 AM
If you instantiate a field with a value, which was supplied in constructor parameter, then the latter is pretty much "outer"
p

Pavlo Liapota

10/08/2018, 9:18 AM
But why would you like to access
this
anyway? Potentially no field will be initialized at this point.
e

Egor Trutenko

10/08/2018, 9:19 AM
Exactly ^