Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do datatype inheritance in Clojure?

For example if I have two different records, but they share a handful of common fields, is there a way to make both records share a common base record? It seems like protocols only allow for declaring method signatures.

like image 966
Chris Avatar asked Dec 12 '11 02:12

Chris


People also ask

Does Clojure have inheritance?

Clojure does not support implementation inheritance. Multimethods are defined using defmulti, which takes the name of the multimethod and the dispatch function. Methods are independently defined using defmethod, passing the multimethod name, the dispatch value and the function body.

What is Defrecord Clojure?

Clojure allows you to create records, which are custom, maplike data types. They're maplike in that they associate keys with values, you can look up their values the same way you can with maps, and they're immutable like maps.


2 Answers

I don't think that is possible as of now.

defrecord is just a macro and you can check what it does by using macroexpand, something like:

(macroexpand '(defrecord User [Name Age]))

So if you want such record inheritance you probably need to implement a macro to do so. But I would not suggest that as inheritance is something that I try to avoid because it leads to complexity.

like image 120
Ankur Avatar answered Nov 13 '22 05:11

Ankur


You should be programming against an abstraction, not particular fields, i.e., use a protocol so the records can share a common interface. E.g., if all of your record types need to return a 'string' property, then create a protocol with a 'get-string' method and extend that to each record type.

(defprotocol SQL
  (get-string [t]))

(defrecord Thing [name f1 f2]
  SQL
  (get-string [t] (str name)))

(defrecord AnotherThing [name f1 f2 f3 f4 blah]
  SQL
  (get-string [t] (str name)))

If you find yourself creating the same implementation for a particular protocol method you can always 'defn-' (non-public function) the implementation and use it as the implementation in each record type.

like image 44
solussd Avatar answered Nov 13 '22 04:11

solussd