Created
October 8, 2019 07:42
-
-
Save nea89o/4966edbdb21cb34f3e823e33c9a5c422 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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