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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Clojure: Destructuring

Trending

  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance
  • How an AI Software Factory Works: From Developer Intent to Production
  • Delta Lake UniForm to Snowflake: Cross-Platform Table Access Without a Second Copy
  • Spring AI on Local LLMs

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Object-oriented Clojure

Object-oriented Clojure

By 
Giorgio Sironi
·
Jan. 10, 12 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook