Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (int 10) produce a Long instance?

Why does (int 10) not produce an instance of type java.lang.Integer?

; why Long here?
=> (type (int 10))
; java.lang.Long

; this one is also Long, why not java.lang.Number?
=> (type (num 10))
; java.lang.Long

=> (type (double 10))
; java.lang.Double
=> (type (long 10))
; java.lang.Long
=> (type (float 10))
; java.lang.Float
=> (type (short 10))
; java.lang.Short
=> (type (bigint 10))
; clojure.lang.BigInt
=> (type (bigdec 10))
; java.math.BigDecimal
=> (type (boolean 10))
; java.lang.Boolean
=> (type (char 10))
; java.lang.Character
=> (type (byte 10))
; java.lang.Byte
like image 903
Eric Schoonover Avatar asked Feb 26 '12 21:02

Eric Schoonover


Video Answer


2 Answers

Clojure deals only with long integers internally. (int) is used to cast a long to an int for calling Java methods that expect an int argument.

In this case (int 10) does indeed return a Java int, but Clojure then promotes the int back to a long. (type) uses (class) to find out the type of its argument (in this case), and therefore the long gets boxed into a java.lang.Long.

You can produce java.lang.Integer by using one of the java.lang.Integer constructors or factory methods:

user> (type (Integer. 10))
java.lang.Integer

user> (type (Integer/valueOf 10))
java.lang.Integer

user> (type (Integer/decode "10"))
java.lang.Integer

...

(num) will upcast its argument to the abstract class java.lang.Number, but (type) will return the actual type of its argument, i.e. java.lang.Long again.

like image 118
liwp Avatar answered Sep 18 '22 08:09

liwp


int is a cast to primitive integer for interop calls. Since each of type calls takes an Object things get boxed again and Clojure (>= 1.3) boxes to Long and Double. If you need an Integer you have to create one.

user=> (type (Integer/valueOf 10))
java.lang.Integer
like image 32
kotarak Avatar answered Sep 22 '22 08:09

kotarak