Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure functions, let & return values

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.))) 
like image 818
Toby Hede Avatar asked Feb 24 '23 17:02

Toby Hede


1 Answers

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

like image 134
pmdj Avatar answered Mar 06 '23 00:03

pmdj