Working with Java classes
As will be known by now, Clojure is not an object-orientated language. The Clojure team added several features to Clojure to ensure that Clojure can properly consume and create classes from the Java class library and other JVM libraries.
To create an instance of a class, two forms are supported. First, to do this, use new
:
(def x (new java.util.ArrayList () ))
Here we define a variable that points to an ArrayList
instance. By passing an empty list ()
method, we do not pass any parameter to its constructor. A different way to create an instance is to add a dot to the class name:
(def x (java.util.ArrayList. () ))
Note the dot added to ArrayList
. There's no functional difference between the two ways.
Note
Think twice before using mutable collections in a Clojure program. Since Clojure is a functional programming language, it is usually a much better idea to use Clojure's immutable collections whenever possible.
To call methods on the instance of an object, you can prefix...