Say you want to coerce a string to an integer or a float. There’s a good chance you’ll have come across the following suggestions for doing this:

(Integer. "1") ;; => 1
(Float. "1.0") ;; => 1.0

Works, slightly ugly, but works. Or does it? Here’s the catch: these two expressions will throw reflections warnings… which isn’t good performance-wise!

Where does the reflection warning come from? As you may know, it’s due to Clojure having to figure out what the type of things is:

  • Integer. is a constructor which theoretically expects any kind of input
  • "1" is a dynamically typed string. That is, the compiler doesn’t know in advance what kind of object it is.

The issue comes from Integer. having to figure out what exactly is the type of "1" (this is called reflection).

The solution is simply to call the right static method1:

(defn str->int [s]
  (Integer/parseInt s))

(defn str->float [s]
  (Float/parseFloat s))

Here you’re basically telling the compiler to just go ahead and directly use the parseInt/parseFloat methods of the Integer and Float objects, which only accept strings!

This makes the compiler’s job much easier and fast! How amazing!

1: if you don’t know what a static method is, don’t worry too much. I’ll try and write an article on basic Java concepts and interop at some point ^^

Update: Removed the type hinting, as @nikitonsky pointed out that parseInt and parseFloat aren’t overloaded :D