Did you know about with-open?

I decided to start a series of small posts showing some nice features of Clojure, you maybe didn't know. This won't be earth shaking things or big discussions. Just some small snippets and simple facts which are mostly trivial but not necessarily obvious.

Feel free to drop me an email if you think you have something fitting in such a post.

But let's start…

Did you know about `with-open`?

with-open is a nice little helper which takes care to close all sorts of streams. That way you don't have to do all the try/catch boilerplate yourself. However a little known fact is that with-open takes several bindings at once. It closes all streams in reverse order. So instead of…

(with-open [some-stream (get-a stream)]
  (with-open [some-other-stream (get-a another-stream)]
    ; Do stuff
    ))

… you can simply write:

(with-open [some-stream       (get-a stream)
            some-other-stream (get-a another-stream)]
  ; Do stuff
  )

Neat, eh?

Post inspired by this thread.

Published by Meikel Brandmeyer on .