Why does Clojure have 5 ways to define a class instead of just one?

前端 未结 2 1117
难免孤独
难免孤独 2020-12-22 17:29

Clojure has gen-class, reify, proxy and also deftype and defrecord to define new class-like datatypes. For a language that values syntactic simplicity and abhors unnecessary

2条回答
  •  隐瞒了意图╮
    2020-12-22 17:46

    This is a mix of three different factors:

    1. The particular type system of the jvm
    2. The need for slightly different semantics for different use cases when defining types
    3. The fact that some of these were developed earlier, and some later, as the language has evolved.

    So first, let's consider what these do. deftype and gen-class are similar in that they both define a named class for ahead-of-time compilation. Gen-class came first, followed by deftype in clojure 1.2. Deftype is preferred, and has better performance characteristics, but is more restrictive. A deftype class can conform to an interface, but cannot inherit from another class.

    Reify and proxy are both used to dynamically create an instance of an anonymous class at runtime. Proxy came first, reify came along with deftype and defrecord in clojure 1.2. Reify is preferred, just as deftype is, where the semantics are not too restrictive.

    That leaves the question of why both deftype and defrecord, since they appeared at the same time, and have a similar role. For most purposes, we will want to use defrecord: it has all the various clojure goodness that we know and love, sequability and so forth. Deftype is intended for use as a low level building block for the implementation of other datastructures. It doesn't include the regular clojure interfaces, but it does have the option of mutable fields (though this isn't the default).

    For further reading check out:

    The clojure.org datatypes page

    The google group thread where deftype and reify were introduced

提交回复
热议问题