DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Clojure: Destructuring

Trending

  • Automatic Code Transformation With OpenRewrite
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Data Quality: A Novel Perspective for 2025
  • Why Database Migrations Take Months and How to Speed Them Up
  1. DZone
  2. Coding
  3. Java
  4. Object-oriented Clojure

Object-oriented Clojure

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Jan. 10, 12 · Interview
Likes (2)
Comment
Save
Tweet
Share
13.5K Views

Join the DZone community and get the full member experience.

Join For Free

Clojure is a LISP dialect, and as such a functional language based on a large set of functions and a small set of data structures that they operate with.

However, it is possible to implement classes and object in Clojure, with constructs well-supported in the language itself. I do not claim you should program in Clojure only with the techniques described in this article: they are just an attempt to bridge Java libraries with Clojure, and to introduce objects and interfaces where needed.

Java interoperability

Even from the Clojure REPL, you can easily instantiate Java classes as long as they are in the classpath (so use lein if they are in a library)
(def ford (Car. arg1 arg2))
Since classes usually reside into packages, in real code you would use their fully qualified name:
(def ford (com.dzone.example.Car. arg1 arg2))
You can also call methods:
(.brake ford arg1 arg2)

The first argument of the evaluation of a .methodName is always the object, while additional arguments are placed after it, in the same s-expression (a fancy name for a list that can be evaluated.)

One of the first exercises in the book The Joy of Clojure is an instantiation of a java.awt.Frame object and a rendering done on it, all from the Clojure interactive interpreter. Doing exploratory testing classes and objects for Java development with the REPL is as faster as writing code into JUnit test.

Define your own: interfaces

defprotocol takes as the first argument an identifier, and a variable number of parameters. Each of this parameters is a method definition like you would do with fn, but without the fn keyword itself and a body to evaluate.

The first argument of the methods should always be this, representing the current object (remember Python?).

(defprotocol Position
    (description  [this])
    (translateX   [this dx])
    (translateY   [this dy])
    (doubleCoords [this])
    (average      [this another]))

Define your own: classes

Defining classes in Clojure is simple, at least when they implement immutable Value Objects. defrecord takes a class name, a list of parameters for the constructor, an optional protocol name and a variable number of arguments representing the methods.

Again, the methods definition are similar to the ones made with fn, but this time with a body, an s-expression to evaluate. There is a catch: you can only implement methods defined in a protocol.

(defrecord CartesianPoint [x y]
    Position
        (description    [this]      (str "(x=" x ", y=" y ")"))
        (translateX     [this dx]   (CartesianPoint.    (+ x dx)
                                                        y))
        (translateY     [this dy]   (CartesianPoint.    x
                                                        (+ y dy)))
        (doubleCoords   [this]      (CartesianPoint.    (* 2 x)
                                                        (* 2 y)))
        (average        [this another]
                        (let [mean (fn [a b] (/ (+ a b) 2))]
                             (CartesianPoint. (mean x (:x another))
                                              (mean y (:y another))))))

The method access the (immutable) fields of the current object with their names, so this is not probably necessary if not for calling other methods on the object.

Note that records are not strictly objects in the OO sense, since they do not encapsulate their fields: fields can be accessed anywhere with (:fieldname object).

Here's how to work with CartesianPoint objects:

(deftest test-point-x-field
    (is (= 1
           (:x (CartesianPoint. 1
                                2)))))
(deftest test-point-y-field
    (is (= 2
           (:y (CartesianPoint. 1
                                2)))))
(deftest test-point-to-string
    (is (= "(x=1, y=2)"
           (description (CartesianPoint.    1
                                            2)))))
(deftest test-point-translation-x
    (is (= (CartesianPoint. 11 2)
           (translateX  (CartesianPoint.    1
                                            2)
                        10))))
(deftest test-point-translation-y
    (is (= (CartesianPoint. 1 12)
           (translateY  (CartesianPoint. 1
                                        2)
                        10))))
(deftest test-point-doubling
    (is (= (CartesianPoint. 2 4)
           (doubleCoords (CartesianPoint.   1
                                            2)))))
(deftest test-points-average
    (is (= (CartesianPoint. 3
                            4)
           (average (CartesianPoint. 1
                                     2)
                    (CartesianPoint. 5
                                     6)))))
Clojure

Opinions expressed by DZone contributors are their own.

Related

  • Clojure: Destructuring

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: