Deepak Tatyaji Ahire
Deepak Tatyaji Ahire

Reputation: 5309

Is var in Clojure is stored as an object?

Is var in Clojure is stored as an object?

Question 1: If yes, then object of which class?

Question 2: In Java, we have references stored on the thread stack and the they refer to the objects stored on process heap. How to interpret vars in Clojure like the analogy of objects in Java.

EDITS:

To try the first question by myself, I used type/class to check the class of the object.

Case 1:

(def a 100)
(type a)

O/P: java.lang.Long

In this case, it is clear that a is an object of Long class.

But, how to check the same thing for functions. For example -

case 2:

(type identity)

O/P:

clojure.core$identity

So, from the case 2, type returns the namespace instead of class.

How to get the class?

Upvotes: 0

Views: 206

Answers (2)

Alan Thompson
Alan Thompson

Reputation: 29958

Updated - typed original answer too quickly


The concept of a "Var" is built into the Clojure language/compiler. A Var is normally accessed via a namespaced symbol. Each namespace is implemented like a map, where the map keys are Clojure symbols and the map values are Clojure Var objects.

Each Var object is a mutable object that points to an immutable Clojure "value" (eg 5, [1 2 3], {:a 1 :b 2} etc).

Please see this list of documentation sources, esp "Getting Clojure". For the nitty gritty details, look into the Clojure namespace and its implementation.

Upvotes: 0

cfrick
cfrick

Reputation: 37008

If you call (type x) on some previously defined x, then you are using the value of x. If you want to find out about the type of the var, you need to look at the var:

user=> (type #'a)
clojure.lang.Var

A naive way to get information about object is the bean function

user=> (bean #'a)
{:watches {}, :validator nil, :public true, :threadBinding nil, :bound true, :dynamic false, :macro false, :class clojure.lang.Var, :rawRoot 42, :tag nil}

Finding out about the hierarchy via parents:

user=> (parents (class #'a))
#{java.io.Serializable clojure.lang.IFn clojure.lang.Settable clojure.lang.IRef clojure.lang.ARef}

Everything in the JVM is an Object-descendant (except the primitive types).

Upvotes: 2

Related Questions