How to reference the top-level `status` val inside...
# getting-started
d
How to reference the top-level
status
val inside the
apply
lambda?
Copy code
val status: Int = 2
class Test(var status: Int)
Test(1).apply { status = status }
This version leads to self-assignment inside the class.
g
Copy code
val status: Int = 2
class Test(var status: Int)
Test(1).apply { this.status = status }
"On my PC"
status
is resolved as the first value. So I need to specify the property instead of value.
d
Interesting, it indeed behaves differently in different environments. I can simulate my problem in the scratch file but not e.g. in the playground...
Ok. So here's a reproducer more similar to my actual situation: https://pl.kotl.in/A_1sVAhbc
Copy code
class XXX {
    val status: Int = 2

    class Test {
        var status: Int = 1
    }

    fun test() {
        val test = Test().apply { status = status }
        println(test.status)
    }
}

fun main() {
    XXX().test()
}
Prints 1, I want it to print 2.
k
You need
status = this@XXX.status
because the implied
this
inside your lambda refers to the innermost class, Test.
Another way is
val test = Test().also { it.status = status }
d
Of course. I don't know why I have mistakenly written at first that my
val status
is top-level 🤦 Thanks
k
Now I'm wondering, if
val status
was a top-level declaration, and we used
also { status = ???.status }
, how can we un-shadow the name so that it refers to the top-level
status
?
r
I don't know why I have mistakenly written at first that my
val status
is top-level
It's probably the Scratch file you mentioned, iirc they cause some implicit wrapping into classes (probably an artefact from Java)
đź’ˇ 1
👆 2
d
@Klitos Kyriacou you can specify fully qualified name (with package)
d
One of those “yeah, there is a way, but best just avoid needing to do it in the first place” type of situations. Don’t get me wrong, I love knowing this kind of esoterica, but wouldnt want to use or see it in real code.