This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
boot.user=> (def add-and-get #_=> (let [ai (java.util.concurrent.atomic.AtomicInteger.)] #_=> (fn [y] (.addAndGet ai y)))) #'boot.user/add-and-get boot.user=> (add-and-get 2) 2 boot.user=> (add-and-get 2) 4 boot.user=> (add-and-get 7) 11 boot.user=>
I don't understand, shouldn't there be multiple ai instance every time add-and-get is called?
your def creates one ai and returns a fn that uses it. the
def is only evaluated once, so you get one ai. add-and-get is a fn var - when you call it you call the one fn that was created when your
def was evaluated.
add-and-get IS a function, the def can be equivalently written as:
since let returns its last form.
(let [ai (java.util.concurrent.atomic.AtomicInteger.)] (def add-and-get (fn [y] (.addAndGet ai y))))
iow the value of add-and-get is not just a function, it's a closure. https://en.m.wikipedia.org/wiki/Closure_(computer_programming)