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
(nstemp2020toss.dogo)
(defprotocolBark
"Just a protocol"
(barking[this]"bark")
(hungry[this]"hangry")
(sleeping[this]"zzzz"))
(defrecordDog[breed^Integeragecolor]
Bark
(barking[this](str"barking my breed ... "(:breedthis)))
(hungry[this](str"I'm so hungry I could age one whole year to ... "(str(inc(:agethis)))))
(sleeping[this](str"Really tired, and it has nothing to do with my fur color that is "(:colorthis)))
)
Now let’s use the dog object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
(nstemp2020toss.core
(:gen-class)
(:require[temp2020toss.dogo]
[temp2020toss.dogo:refer:all])
(:import(temp2020toss.dogoDog)))
(defn-main
"I don't do a whole lot ... yet."
[&args]
(println"Hello, World!")
(let[my-dog(Dog."chow"8"green")]
(println"-->"(:breedmy-dog))
(println"-->"(barkingmy-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.
I absolutely love the user razvan’s Clojure
defrecord example over at stackoverflow, so I copied it here. I know I’ll never find it again if I don’t. Look at the original over on stackoverflow at this link.