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?
dephinera
03/21/2021, 2:52 PM
Is this a hack?
y
Youssef Shoaib [MOD]
03/21/2021, 2:57 PM
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
dephinera
03/21/2021, 3:02 PM
Okay, I think I got it. Basically if I define the function outside the class, then it will work. That makes sense, thanks
s
streetsofboston
03/21/2021, 3:50 PM
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).