Clojure Record Heirarchy

In Clojure, if you want a basic OOP behavior without killing yourself to fully implement Java classes and interfaces in Clojure, the preferred technique is to use records. Sometimes implementing protocols in records suits your needs, mostly due to speed of code execution. However, if you want polymorphism with your records, then multimethods are where it’s at.

Admittedly, multimethods are very flexible, so the technique I’ll show you is one of many techniques you could use. The basic pattern I use for inheritance with records, is to use the derive  command with keywords that are kept as a value in the record. For example,

type  is used to track isa  relationships of ::food  and ::fruit . derive  is used to set ::food  as the parent of ::fruit . Notice the use of custom constructors to set default values for type  in the records.

Now, let’s integrate this with a little polymorphism via multimethods.

Remember, keywords act as functions when dealing with records. So, we use :type  to get the values of type  in foods and fruits. Then the multimethods sort out the polymorphism needed to call the right functions.

We can use the records and multimethods with the following code.

The output of the above code should look something like the following.

And there you have a little polymorphism using records and multimethods.

For convenience here is the entire code sample with namespace and import included.

 

 

Leave a Reply

Your email address will not be published.