polish context-receivers.md
Serendipithub opened this issue · 1 comments
Serendipithub commented
- Conveniently scoping automatically closeable resources (flexible “try-with-resources”)
interface AutoCloseScope {
fun defer(closeBlock: () -> Unit) //there be defer
}
context(AutoCloseScope)
fun File.open(): InputStream
fun withAutoClose(block: context(AutoCloseScope) () -> Unit) {
val scope = AutoCloseScopeImpl() // Not shown here
try {
with(scope) { block() }
} finally {
scope.close() //there be close
}
}
// usage
withAutoClose {
val input = File("input.txt").open()
val config = File("config.txt").open()
// Work
// All files are closed at the end
}
I think the two methods (defer, close) should be the same name for easier understanding.
elizarov commented
That's just an example of how it might be used, not a polished design. Anyway, those two methods cannot have the same name, since they do completely different things -- defer
registers a block to be called on close, while close
calls all the blocks registered by defer. They might share some elements of their name, though.