Is Clojure consistent? does the function return only true if the things being compared are actually the same instance?

I thought that

(identical? xy) 

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

 (def moo 4) (def cow 4) (identical? moo cow) true 

But I thought that both mu and cows are separate instances of the integer "4"? What gives?

+5
source share
1 answer

In the JVM, two equal integers between -128 and 127 always the same because it supports IntegerCache .

This means that two equal integers from -128 to 127 are always the same instance of the 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 information.

+8
source

Source: https://habr.com/ru/post/1202529/


All Articles