4
votes

I understand what :state /does/. It creates a field, like in Java, in your class. What I don't understand is what is the point of this? It seems like I only see it done with Clojure-generated classes that extend other classes. http://www.fatvat.co.uk/2009/05/clojure-and-robocode.html being one example. I don't know Java, and I'm not very well versed in Object Oriented Programming. Can someone explain the point of :state to me, and where it all fits in with Java interop?

Thanks a lot!

NOTE: When I say :state, I am referring to (:gen-class :state)

3

3 Answers

4
votes

:state is simply a way of sharing some data between the functions generated as part of gen-class. Think of it as being exactly the same as the instance data of an object.

3
votes

More infomation on the state and how to initialize it can be found the article gen-class – how it works and how to use it

From the article:

  • :state defines a method which will return the object's state.
  • :init defines the name of the initialiser. This is a function which has to return a vector. The first element is again a vector of arguments to the super class constructor. In our case this is just the empty vector. The second element is the object's state.

In summary, init returns the state of the object and is called when the object is instantiated. state is a method on the class, as opposed to a function, that will return the same value returned as the second element in the vector returned by init.

The article then goes on to show how to use an atom to be able to change the state of the object, if needed.

2
votes

I talked it over with hiredman on the #Clojure IRC channel, and he told me that the main point of it is a state per instance. That makes sense.