murtaza52
murtaza52

Reputation: 47441

binding vs with-bindings in clojure

There are two macros binding and with-bindings to redefine dynamic vars. However both seem to have the utility, what is the difference between them ?

;; binding
(def :^dynamic a 10)
(binding [a 20] a) ;; => 20
a ;; => 10

;; with-bindings
(with-bindings {#'a 20}
  a) ;; => 20
a ;; => 10

both of them are changing the per thread dynamic scope, and resetting it to the root binding after the lexical scope is over.

Upvotes: 1

Views: 271

Answers (1)

Sean Corfield
Sean Corfield

Reputation: 6666

The underlying implementation of both is pretty much identical:

  • push thread bindings (using the bindings supplied)
  • try the body
  • finally pop thread bindings

binding was added in Clojure 1.0 and with-bindings in 1.1. I don't see the latter used in any code tho', just the former.

Upvotes: 2

Related Questions