A hopefully short and concise explanation as to how Clojure deals with Objects. If you already write Clojure, this isn't for you.
You know what an Interface is if you write/read Java or PHP 5+. In Clojure it might be called defprotocol.
user> (defprotocol IABC
(also-oo [this])
(another-fn [this x]))
IABC
You might be tempted to use the classic implements or extends keywords when defining a new Class. In Clojure it might be called defrecord.
user> (defrecord ABC [name]
;; You can implement multiple Classes here
IABC
(also-oo [this]
(str "This => " (:name this)))
(another-fn [this x]
(format "%s says: %s" (:name this) x)))
user.ABC
You might be tempted to use the classic new keyword to instantiate a new object. In Clojure it might be a simple decimal suffix added to the Class name so that it can be used as a predicate.
user> (def a (ABC. "Roger"))
#'user/a
user> (another-fn a "oo programing")
"Roger says: oo programing"
user> (also-oo a)
"This => Roger"
Clojure can just do it better.
user> (defmulti this-is-oo type)
nil
user> (defmethod this-is-oo ABC [this]
(println (:name this)))
#<MultiFn clojure.lang.MultiFn@8625d0e>
user> (this-is-oo a)
Roger
user> (defmethod this-is-oo java.lang.String [this]
"Got a string and not ABC!!!!")
#<MultiFn clojure.lang.MultiFn@8625d0e>
user> (this-is-oo "a")
"Got a string and not ABC!!!!"
This is interesting but I feel like I'm missing something. I'd love to hear more discussion/expansion on this as someone who bought the Clojure book, loves Rich Hickey's talks and yet was completely turned off by the language.
I am unconvinced by the first 3 examples as they are in my opinion significantly less readable than the equivalent code in a C-style, OOP-friendly language such as Ruby or Python with basic
Class
syntax.*Please could you elaborate on the final example as to what you are doing and why it is better.
*I realise readability is subjective and Lispers consciously trade-off 'syntax' (which I tend to believe is necessary for expressiveness & therefore readability) for the benefits of homoiconicity. I'm yet to understand that trade-off as to me homoiconicity offers no practical benefit in the day-to-day, team-building-an-app environment.