Want some Object Oriented Programming in Clojure? Here’s a quick example.
Let’s create a dog object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
(ns temp2020toss.dogo) (defprotocol Bark "Just a protocol" (barking [this] "bark") (hungry [this] "hangry") (sleeping[this] "zzzz")) (defrecord Dog [breed ^Integer age color] Bark (barking [this] (str "barking my breed ... " (:breed this))) (hungry [this] (str "I'm so hungry I could age one whole year to ... " (str (inc (:age this))))) (sleeping [this] (str "Really tired, and it has nothing to do with my fur color that is " (:color this))) ) |
Now let’s use the dog object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
(ns temp2020toss.core (:gen-class) (:require [temp2020toss.dogo] [temp2020toss.dogo :refer :all]) (:import (temp2020toss.dogo Dog))) (defn -main "I don't do a whole lot ... yet." [& args] (println "Hello, World!") (let [my-dog (Dog. "chow" 8 "green")] (println "-->" (:breed my-dog)) (println "-->" (barking my-dog)))) |
See, OOP in Clojure is fairly simple. This sample uses protocols with records, but you can add polymorphism with just a little extra work. For polymorphism, use records and multimethods.