Skip to content

Instantly share code, notes, and snippets.

@wplong11
Created October 26, 2022 14:05
Show Gist options
  • Select an option

  • Save wplong11/e327fec25fcb655e1944ac757a95153e to your computer and use it in GitHub Desktop.

Select an option

Save wplong11/e327fec25fcb655e1944ac757a95153e to your computer and use it in GitHub Desktop.
import java.lang.Exception
fun main() {
runrunrun {
defer { println("HI") }
defer { println("HI") }
defer { println("HI") }
println("HELLO")
println("HELLO")
println("HELLO")
throw Exception("HI")
}
}
fun runrunrun(block: DeferBag.() -> Unit) {
val bag = DeferBag()
try {
bag.block()
} finally {
bag.runAll()
}
}
class DeferBag {
private val list: MutableList<() -> Unit> = mutableListOf()
fun defer(block: () -> Unit) {
list.add(block)
}
fun runAll() {
for (val element in list) {
element()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment