Can I add fields to clojure types?
Asked Answered
H

1

7

Clojure structs can be arbitrarily extended, adding new fields.

Is it possible to extend types (created using deftype) in a similar way?

EDIT: For the benefit future visitors, as Brian pointed out below, this feature is subject to change.

Hurtle answered 19/3, 2010 at 5:41 Comment(1)
deftype is still a work in progress, things are subject to change. See e.g. groups.google.com/group/clojure/browse_frm/thread/…Transaction
S
7

Actually you can treat types as maps, you just need to extend clojure.lang.IPersistentMap (an implementation is magically supplied).

(deftype A [a b]
  clojure.lang.IPersistentMap)
(A 1 2) ;; => #:A{:a 1, :b 2}
(assoc (A 1 2) :c 3) ;; => #:A{:a 1, :b 2, :c 3}

Note

Clojure has since split the semantics of types into defrecord and deftype. For most application-level programming, you'll want to use records. Conveniently, they automatically provide an implementation of clojure.lang.IPersistentMap, no magic necessary.

Seidel answered 19/3, 2010 at 8:9 Comment(2)
This doesn't work in Clojure 1.2, you'll get just get an java.lang.AbstractMethodError, as you would expect without providing any implementation.Karaite
This was valid for an early beta release of Clojure 1.2. I've added a note for mentioning the changes in the final release.Seidel

© 2022 - 2024 — McMap. All rights reserved.