Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: def to Java static function

Tags:

clojure

Consider the following Clojure code:

(defn space? [c] (Character/isWhitespace c))

It's okay. But obviously, this is just another name and refactor in pointless style:

(def space? Character/isWhitespace)

But I get compilation error:

Caused by: java.lang.RuntimeException: Unable to find static field: isWhitespace 
in class java.lang.Character

Why it can't find it? It works perfectly with Clojure functions:

(def wrap-space? space?) ; Compiles OK!

What happens here? Why def with Java static function doesn't work?

like image 403
demi Avatar asked Mar 23 '23 13:03

demi


1 Answers

Your first two statements are actually not equivalent. When you say...

(def space? Character/isWhitespace)

...Clojure is trying to look for a static field (not method) called isWhitespace in java.lang.Character. Of course, no such field exists, which is why you get the compile error.

Other correct ways to rewrite the following statement...

(defn space? [c] (Character/isWhitespace c))

...would be:

  • (def space? (fn [c] (Character/isWhitespace c)))
  • (defn space? [c] (. Character isWhitespace c))

Edit

Just to add, I imagine that the reason Clojure allows (def wrap-space? space?) is because there is no ambiguity about what space? is. A static Java method, on the other hand, could be overloaded with different sets of parameters, or could share the same name with a static field. Hence, to alias a static Java method, you have to be explicit about exactly what method/field you're aliasing.

like image 60
Mansoor Siddiqui Avatar answered Apr 02 '23 02:04

Mansoor Siddiqui