I’d like to be able to refer to an object from wit...
# announcements
e
I’d like to be able to refer to an object from within itself, like this:
Copy code
val r: Runnable = Runnable {
        println("In runnable")
        r.run()
    }
(I know the code would generate a stack overflow; it’s an oversimplification of what I really want to do.) How can I do this? Changing
r
from
val
to
var
has no effect. Do I need to create a second variable and make it refer to the first value?
Copy code
lateinit var r2: Runnable

    var r: Runnable = Runnable {
        println("In runnable")
        r2.run()
    }
    
    init {
        r2 = r
    }
d
Convert it from lambda to anonymous object.
c
Make it a
lazy { }
property
🥇 1
e
Thanks, @Dominaezzz, but I still get the error
Variable 'r' must be initialized
with:
Copy code
val r: Runnable = object: Runnable {
        @Override
        override fun run() {
            println("In runnable")
            r.run()
        }
    }
Thanks, @Casey Brooks! That did the trick:
Copy code
val r: Runnable by lazy {
        Runnable {
            println("In runnable")
            r.run()
        }
    }
d
That's what I meant.
Copy code
val r: Runnable = object: Runnable {
        @Override
        override fun run() {
            println("In runnable")
            this.run()
        }
    }
💯 1
🥇 1
e
Thanks a lot, @Dominaezzz!
k
this seems to work: