Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

What is the difference between (class =) and (type =)?
Thnx!

1 Answer

+1 vote
by
selected by
 
Best answer

By using the REPL:

=> (source type)
(defn type 
  "Returns the :type metadata of x, or its Class if none"
  {:added "1.0"
   :static true}
  [x]
  (or (get (meta x) :type) (class x)))
nil
=> (source class)
(defn class
  "Returns the Class of x"
  {:added "1.0"
   :static true}
  ^Class [^Object x] (if (nil? x) x (. x (getClass))))
nil
by
Thanks!
Could you please write example where output of (class Something) <> (type Something)?

:-)
by
Hi Eugene. Maybe this will help:

    (def sym (with-meta 'foo {:type :foo-type-tag}))
    (class sym)
    ;;=> clojure.lang.Symbol
    (type sym)
    ;;=> :foo-type-tag
by
Here's another example: https://clojuredocs.org/clojure.core/type#example-542692cfc026201cdc326e2d

And here's to expand on the above `sym` example on why `type` might be useful:

    => (defmethod print-method :foo-type-tag [v w] (.write w (str "Custom print:" v)))
    #object[clojure.lang.MultiFn 0x3a4ba480 "clojure.lang.MultiFn@3a4ba480"]
    => (println sym)
    Custom print:foo
    nil
...