开发者

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.))) 


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜