Skip to content

Instantly share code, notes, and snippets.

@peter
Last active January 15, 2024 18:45
Show Gist options
  • Select an option

  • Save peter/dce5ce693e1f90924709 to your computer and use it in GitHub Desktop.

Select an option

Save peter/dce5ce693e1f90924709 to your computer and use it in GitHub Desktop.
Example of Clojure Derive/Multimethods for inheritance/polymorphism
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment