Jonathan Olsson
12/15/2023, 10:53 AMdata class A(val x: String = "default") {
fun toObjectNotWorking(): Any {
return object {
// Type checking has run into a recursive problem
val x = x
}
}
fun toObjectWorking(): Any {
val x2 = x
return object {
val x = x2
}
}
}
If I define a type on the value in the object in toObjectNotWorking
I get Variable x must be initalized
. Is there some other syntax to refer to the `x`field defined in A
?ephemient
12/15/2023, 10:57 AMthis@A.x
ephemient
12/15/2023, 10:58 AMJonathan Olsson
12/15/2023, 10:59 AMCLOVIS
12/15/2023, 11:12 AMreturn object {
val x: String = x
}
you get the error Variable 'x' must be initialized
, so the compiler does notice that this is unsafe.
@Jonathan Olsson to avoid such surprises in the future, if you put your cursor on one variable, IntelliJ will highlight all other usages of the same variable (and not other variables that have the same name), so it becomes easy to notice that this is trying to assign x
to itself and not using the x
from A
.ephemient
12/15/2023, 11:21 AMval x
shadows the outer class's val x
so that's what x
means thereephemient
12/15/2023, 11:22 AMclass A(x: String) {
val x: String = x
which is legal because the right-hand x
refers to the constructor parameter, not this.x
ephemient
12/15/2023, 11:25 AMthis
- or this@
-qualified (e.g. parameters, local variables) take precedence over names that can be qualified, and then all this
-qualified names follow nesting and inheritance