I\'m very new to Clojure, Can you guys give me explanation with real world scenarios. I mean, where to use Ref, Var, Agent, Atom. I read book, but, still couldn\'t understan
When I first read about these types, I also struggled to understand where I could or should use each one so here's my plain English answer:
Use a var when the data won't change. This happens whenever you use def
or most functions that start with def
like defn
.
Use an atom when you have a single item that changes. An example might be a counter or a vector that you want to add items to.
Use a ref when you have two or more things that must change at the same time. Think "database transactions" if you are familiar. The canonical example of this is transferring money from one account to another. Each account could be stored in a ref so that changes can be made to appear atomic.
Use an agent when you want something to change but you don't care when. This might be a long computation or writing something to a file or socket. Note that with the latter you should use send-off
.
Note: I appreciate that there is quite a lot more to each of these but hopefully this should give you a starting point.