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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With