The following construct confuses me. ```interface ...
# announcements
d
The following construct confuses me.
Copy code
interface Scope

class Service : Scope {

    fun <T> scoped(block: Service.() -> T): T {
        return block().also {
            finalize()
        }
    }

    fun Scope.foo(): String {
        return "Heya!"
    }

    private fun finalize() {
        // release resources and stuff
    }

}

fun main() {

    val service = Service()

    val res = service.scoped {
        foo()
    }

    service.foo() // ERROR
}
Basically I achieved what I wanted - to be able to call Service's methods only within a scope, so some finalization work can be done automatically, instead of relying on the consumer to do it. However I don't really understand why I can't call
foo
outside the scope. Can anyone explain it, please?
Is this a hack?
y
Well basically
foo
is only defined whenever you are inside of the context of
Service
, and so you can only call foo on a scope if you are inside of a service. To make your code work, you can simply wrap it in
with(service) { service.foo() }
d
Okay, I think I got it. Basically if I define the function outside the class, then it will work. That makes sense, thanks
s
The function
foo
is defined to have multiple (two) receivers (a Service (instance) and a Scope (extension)). Where the error is shown, there's only one receiver (an instance of Service).
🙏 1
👍 2
👍🏻 1