Let's look at a simple example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns test.wrapper | |
(:gen-class | |
:name test.Speak | |
:methods [ | |
[hello [String] String] | |
])) | |
(defn -hello [this name] | |
(str "Hello, " name)) |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns test.wrapper | |
(:gen-class | |
:name test.Speak | |
:state name | |
:methods [ | |
[hello [] String] | |
[setName [name] void] | |
])) | |
(defn -setName[this name] | |
(reset! (.name this) name)) | |
(defn -hello [this] | |
(str "Hello, " (.name this))) |
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