ClojureDocs

Nav

Namespaces

ints

clojure.core

Available since 1.0 (source)
  • (ints xs)
Casts to int[]
2 Examples
(def my-floats (float-array [1.1 2.2 3.3]));; => #'user/my-floats

;; int-array will convert where possible
(int-array my-floats);; => [1, 2, 3]

;; ints will not
(try (ints my-floats)
     (catch ClassCastException e (ex-message e)));; => "[F cannot be cast to [I"
;; Casting avoids expensive reflection, so to see the benefit, enable warning:
(set! *warn-on-reflection* true)

;; We'll def an int-array but won't type-hint the var:
(def my-array (int-array [10 20 30 40 50 60]))

;; and try to amap over it without using `ints` or type hinting:
(amap my-array i _ (unchecked-inc-int (aget my-array i)))
;; Reflection warning… call to static method alength on clojure.lang.RT can't be resolved (argument types: unknown).
;; Reflection warning… call to static method aclone on clojure.lang.RT can't be resolved (argument types: unknown).
;; Reflection warning… call to static method aget on clojure.lang.RT can't be resolved (argument types: unknown, int).
;; Reflection warning… call to static method aset on clojure.lang.RT can't be resolved (argument types: unknown, int, int).
;; => [11, 21, 31, 41, 51, 61]

;; We can use `ints` to avoid reflection:
(amap (ints my-array) i _ (unchecked-inc-int (aget (ints my-array) i)))
;; => [11, 21, 31, 41, 51, 61]

;; Just as we can type hint in place:
(amap ^ints my-array i _ (unchecked-inc-int (aget ^ints my-array i)))
;; => [11, 21, 31, 41, 51, 61]

;; Or type hint the var:
(def ^"[I" my-array (int-array [10 20 30 40 50 60]))
(amap my-array i _ (unchecked-inc-int (aget my-array i)))
;; => [11, 21, 31, 41, 51, 61]
See Also

Creates an array of ints

Added by TimMc
0 Notes
No notes for ints