Is Go's defer possible in Kotlin?


#1

Is something like Go's defer control structure possible in Kotlin? (link: http://golangtutorials.blogspot.tw/2011/06/control-structures-go-defer-statement.html)

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

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


#2

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

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

See code here: http://kotlin-demo.jetbrains.com/?publicLink=1040749715610173087711460271843


#3

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


#4

Good point. Fixed


#5

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?


#6

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

For more information check out this page: http://confluence.jetbrains.com/display/Kotlin/Type-safe+Groovy-style+builders
And this article has an extensive tutorial: http://jaxenter.com/type-safe-web-with-kotlin-47395.html