Zuriar
Zuriar

Reputation: 11734

Does Clojure's identical? function only return true if the things being compared are actually the same instance?

I thought

(identical? x y)

only returns true if both x and y are the same instance? So what about this:

(def moo 4)
(def cow 4)

(identical? moo cow)
true

Yet I thought both moo and cow are separate instances of the integer '4'? What gives?

Upvotes: 5

Views: 174

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51460

In JVM two equal integers between -128 and 127 are always identical, because it maintains IntegerCache.

It means that two equal integers between -128 and 127 are always the same instance of Integer class.

Try comparing different integers:

(identical? 4 (+ 2 2)) ; true
(identical? 127 127) ; true
(identical? 128 128) ; false

See this answer on Code Golf for more info.

Upvotes: 8

Related Questions