![]() |
Peter Marklund's Home |
Using Clojure Multimethods for Polymorphism and Inheritance
It's fascinating how simple and powerful the multimethod feature in Clojure is. It provides a way to support polymorphism and inheritance that we are used to from object oriented languages:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; BASE CLASS | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; public class ContentItem { | |
; public String foobar() { | |
; return "content_item"; | |
; } | |
; } | |
(defn model-type-dispatch [item] | |
(keyword (str "model/" (:type item)))) | |
(defmulti foobar model-type-dispatch) | |
(defmethod foobar :model/content_item [item] | |
"content_item") | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; CHILD CLASS - OVERRIDES METOHD | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; public class Chef extends ContentItem { | |
; public String foobar() { | |
; return "chef"; | |
; } | |
; } | |
(derive :model/chef :model/content_item) | |
(defmethod foobar :model/chef [item] | |
"chef") | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; CHILD CLASS - WITHOUT OVERRIDE | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; public class Source extends ContentItem { | |
; } | |
(derive :model/source :model/content_item) | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; MAIN | |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
; public static void main(String[] args) { | |
; System.out.println(new ContentItem().foobar()); | |
; System.out.println(new Chef().foobar()); | |
; System.out.println(new Source().foobar()); | |
; } | |
(foobar {:type "content_item"}) ; => content_item | |
(foobar {:type "chef"}) ; => chef | |
(foobar {:type "source"}) ; => content_item | |
(isa? :model/chef :model/content_item) ; => true | |
(isa? :model/source :model/content_item) ; => true |