Striking a More Specific Bargain with Records

Happily, Clojure provides an alternative to maps that mitigates some of these shortcomings: the record. You can think of records as maps with some predefined keys. To make a record you need to first define the record type:

 (defrecord FictionalCharacter[name appears-in author])

As you can see from the code, the record type has a name and a list of the predefined fields. So if you evaluate the expression in our example, you end up with a record type called FictionalCharacter that has three fields, one for the character’s name, one for the name of the fictional work the character appears in, and one for the author. Behind the scenes, defrecord creates a couple of functions, whose names are based on ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.