deftype vs. defrecord
Asked Answered
F

2

37

While defrecord is the preferred form -for the general case- in Clojure for defining an "entity", in ClojureScript one can find far more references to deftype, as reflected in various documentation.

What is the difference between both forms? Which should one prefer?

Flanna answered 31/10, 2012 at 2:46 Comment(0)
E
50

deftype creates a bare-bones object which implements a protocol.

defrecord creates an immutable persistent map which implements a protocol.

Which to use depends on what you want. Do you want a full ClojureScript data structure? Then use a record. Do you just want a bare-bones thing that does nothing but satisfy a protocol? Then use a type.

The two bits of documentation you reference use types because they're trying to illustrate protocols at the most basic level, and types have less "going on" than records, so to speak.

However, most real-world uses of object-like things in Clojure/ClojureScript need to store fields of data along with the object, and for that you should emphatically use a record, for the same reason you should use any of Clojure's immutable collections.

Emmaline answered 31/10, 2012 at 20:40 Comment(1)
according to the document and quick repl inspect, defrecord doesn't create map, defprotocol does. deftype and defrecord both create class with immutable fields deftype doc, defrecord doc.Occurrence
G
2

According to DEFTYPE VS DEFRECORD, you should distinguish programming constructs and domain constructs.

deftype is for programming constructs and defrecord is for domain constructs that need a custom type.

Hope this helps.

Gnathous answered 1/2, 2019 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.