There's been a lot said about using Java in Clojure code. However, the circumstance may arise when you need to write Clojure code to run in Java. It is a little more roundabout and a little less clean, but it is possible. I'll be going over the gen class option available for the interop to take place.
Let's look at a simple example.
What we have available now is a package test with class Speak. We can instantiate an instance of speak. We can call hello("my name") on our instance and I'm sure you can guess what happens. One caveat to notice is that we must prepend our function names with '-' and we must declare our function's in the top gen-class block. We can then get a little fancier. Here's the same example with a global variable.
Now we can set the name on our instance before we call the speak function. Notice the :state declaration in the top block. We can only have one state variable, so use it wisely. Here, I intend to only use it to hold the name to say hello to. A good pattern is to use the state option to store a map of all the variables one might need since we are limited to one state variable.
No comments:
Post a Comment