1

Here's a Clojure REPL session:

moon.core> Double
java.lang.Double
moon.core> (Double/parseDouble "1.0")
1.0
moon.core> Double/parseDouble
CompilerException java.lang.RuntimeException: Unable to find static field: parseDouble in class java.lang.Double, compiling:(*cider-repl moon*:1:7159) 

I'm able to reference Double, and I'm able to call Double/parseDouble, but I can't directly reference it. I see the same result for other class methods in the Java standard library (e.g. Math/abs, Integer/parseInt). the Why is that?

Brendan
  • 1,995
  • 1
  • 20
  • 35

2 Answers2

5

If you want to turn a static Java method into a Clojure function that you can treat as a first class thing, you can easily wrap a function around it:

(def pd #(Double/parseDouble %))
#'user/pd
(pd "1.0")
1.0

The memfn function can be used to do something like this for Java instance methods.

Alex Miller
  • 69,183
  • 25
  • 122
  • 167
3

This doesn't work (in the REPL or otherwise), because there is no static field called parseDouble on the Double class. parseDouble is a method. You can call it, but you can't access it like a field.

Nathan Davis
  • 5,636
  • 27
  • 39
  • Interesting. I'm confused by the fact that I can reference (without calling) Clojure functions but not Java methods. – Brendan Nov 20 '16 at 19:18
  • Yep, Clojure functions and Java methods are entirely different (from an implementation point of view). IIRC, the ability to automatically generate a Clojure function from a static method was considered, but ultimately rejected for pragmatic reasons. – Nathan Davis Nov 20 '16 at 19:58