4

Is it unwise to return a var bound using let?

(let [pipeline (Channels/pipeline)]
  (.addLast pipeline "codec" (HttpClientCodec.))
  ;; several more lines like this
  pipeline)

Is the binding here just about the lexical scope (as opposed to def) and not unsafe to pass around?

Update In writing this question I realised the above was ugly. And if something is ugly in Clojure you are probably doing it wrong.

I think this is probably the more idiomatic way of handling the above (which makes the question moot, btw, but still handy knowledge).

(doto (Channels/pipeline)
  (.addLast "codec" (HttpClientCodec.))) 
2
  • 1
    doto doesn't really make this question moot, because the version of your code using doto expands to the same thing as your original version. But it does tell you that it must be perfectly okay to do this, or else doto wouldn't be written this way! Commented Mar 26, 2011 at 1:07
  • Yes, that's what I meant, and why I left the question answer here for future generations :D. The idiomatic expression reveals the underlying structure. Commented Mar 26, 2011 at 2:49

1 Answer 1

8

let is purely lexically scoped and doesn't create a var. The locals created by let (or loop) behave exactly like function arguments. So yeah, it's safe to use as many let/loop-defined locals as you like, close over them, etc. Returning a local from the function simply returns its value, not the internal representation (which is actually on the stack, unless closed over). let/loop bindings are therefore also reentrancy/thread-safe.

By the way, for your specific code example with lots of java calls, you may want to consider using doto instead or additionally. http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/doto

Sign up to request clarification or add additional context in comments.

1 Comment

I almost beat you to the "doto" :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.