3

I am getting this complaint when passing Integer constructor to map function :

=> (map Integer. ["1" "2" "3"])
CompilerException java.lang.ClassNotFoundException: Integer., compiling:(NO_SOURCE_PATH:1:1) 

However when I wrap the constructor in a function everything works:

=> (defn str-to-int [str] (Integer. str))
=> (map str-to-int ["1" "2" "3"])
(1 2 3)

Why do I have to wrap Integer in another function to make this work? Is there a better way to make it work without creating additional function?

Viktor K.
  • 2,670
  • 2
  • 19
  • 30

2 Answers2

3

map takes in a function and interop uses a special forms like new . and .. It is fairly easy to wrap these with anonymous function literals

for example

(map #(Integer. %) ["1" "2" "3"])

produces the desired result.

KobbyPemson
  • 2,519
  • 1
  • 18
  • 33
1

without java interop. if you just need to convert to digits.

; nrepl.el 0.2.0 (Clojure 1.5.1, nREPL 0.2.3)
user> (map read-string ["1" "2"])
(1 2)
user> (class (first *1))
java.lang.Long

Or if you really need Integer class

user> (map (comp int read-string) ["1" "2"])
(1 2)
user> (class (first *1))
java.lang.Integer
jcalloway
  • 1,155
  • 1
  • 15
  • 24