Is Go's defer possible in Kotlin?


Is something like Go's defer control structure possible in Kotlin? (link:

If not, could I make it a feature request? :slight_smile:

Or, should I just stick with try/catch/finally?


You can do something similar as a library function, like:

withDefers {   foo()   defer { bar() }   baz() }

See code here:


Because Golang's defer is a LIFO structure you must change your done function to

fun done() {   for (action in actions.reverse()) {           action()   } }

Or using a Stack structure instead of list


Good point. Fixed


Very nice.  One question, what is going on in L13-17? Is that some short cut to declaring an extension method? I have also not seen the "WithDefers.() -> ..…" syntax on L36 before, is saying type is a method of WithDefers?


This is called "type-safe builders". Essentially these are function calls that take lambdas as arguments.

For more information check out this page:
And this article has an extensive tutorial: