Extending Java Class in Clojure

less than 1 minute read

Code

;; extend_java_class.clj

(defprotocol Wishy
    (wish [this]))

(extend-type String Wishy
    (wish [this] (str "Hello " this "!")))

(wish "Karthik")

(wish 1) ; puts out an error

(extend-type java.lang.Long Wishy
    (wish [this] (str this " is a great number!")))

(wish 1)

(defprotocol Greeting
  (greet [this])
  (hello [this]))

(extend-type String Greeting
  (greet [this] (str  this "!" " Hope you are doing good!!"))
  (hello [this] (str "Hello " this "!")))

(greet "Karthik")

(hello "Karthik")

Updated: