Skip to content

Instantly share code, notes, and snippets.

@nea89o
Created October 8, 2019 07:42
Show Gist options
  • Save nea89o/4966edbdb21cb34f3e823e33c9a5c422 to your computer and use it in GitHub Desktop.
Save nea89o/4966edbdb21cb34f3e823e33c9a5c422 to your computer and use it in GitHub Desktop.
import java.io.Closeable
import java.util.*
class ResourceContext {
private val toClose = mutableListOf<Closeable>()
fun <A : Closeable> open(thing: A): A {
toClose.add(thing)
return thing
}
fun onExit() {
throw toClose.map {
try {
it.close()
null
} catch (e: Exception) {
e
}
}.firstOrNull() ?: return
}
}
inline fun <R> tryWithManyResourcesContext(block: ResourceContext.() -> R): R {
val ctx = ResourceContext()
try {
return ctx.run(block)
} finally {
ctx.onExit()
}
}
fun main() {
val text = tryWithManyResourcesContext {
val scanner = open(Scanner(System.`in`))
return@tryWithManyResourcesContext scanner.nextLine()
}
println(text)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment