How to create a Java object in Clojure
Overview
Since Clojure ends up running on a Java virtual environment, it is no surprise that we can create a Java object.
Create a Java object in Clojure
We can do this using the new keyword, just as it is done in Java programming.
Syntax
(def variablename(new Objectname))
The syntax for creating a java object in Clojure
Parameters
Objectname: This is the major parameter for creating a Java object using Clojure.
variablename: This is used to hold the instance of the object on creation.
Return value
This keyword will create a new object, which will return a Java object.
Example
(ns Project(:gen-class))(defn func [](def obj(new Integer 1))(println (+ 5 obj)))(func)
Explanation
- Line 3: We create a function,
func. - Line 4: We create an integer object
obj, and we assign it to1. - Line 5: We add
5to the newly created object, and we print it out usingprintln().