dephinera
03/21/2021, 2:43 PMinterface 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 PMYoussef Shoaib [MOD]
03/21/2021, 2:57 PMfoo
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() }
dephinera
03/21/2021, 3:02 PMstreetsofboston
03/21/2021, 3:50 PMfoo
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).