Pure Danger Tech


navigation
home

Using records from a different namespace in Clojure

30 Jun 2010

This is something that took me a bit of exploration to figure out so maybe this will help someone.

Records are a new feature of Clojure 1.2 that allow you to dynamically generate a compiled Java class with a specific set of fields that can be used as a map with :keyword keys for the fields. It’s still in a bit of flux but it has a lot of nice improvements over the older struct support.

The defrecord macro creates a Java class under the hood and is instantiated just like a Java class (at least for now):

user=> (defrecord Nachos [cheese jalapenos])
user.Nachos
user=> (Nachos. "cheddar" "yes")
{:cheese "cheddar",
 :jalapenos "yes"}

If you create some records in a particular namespace, say in food/nachos.clj:

(ns food.nachos)
(defrecord Nachos [cheese jalapenos])

then to access that record from another ns, you will definitely need to import the Java record, but also require the namespace to ensure that the class is actually generated. You might be able to get around that require with :gen-class, I’m not sure.

(ns food.feast
  (:require [food.nachos])
  (:import [food.nachos Nachos]))

...

I think that’s right, but please correct me if I’m misunderstanding.