4

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?

2
  • If you really wanted to use def, you would have to use an anonymous function: (def space? #(Character/isWhitespace? %)). Commented Sep 4, 2013 at 14:46
  • @Alex This is still not point-free notation which I tried to reach. I considered this variant too, thanks. Commented Sep 4, 2013 at 18:30

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The edit is especially useful. Although, I think it's better to have error message about ambiguity. It's more clear.
Due to the possibility of ambiguity, it doesn't even look for a method unless in the calling position. Though I would agree clojure errors in general are often unhelpful. I think the semantic difference is that all clojure functions are objects, while methods are attached to some other object, and while we like things to be first class, there is no reason to treat something as first class when (like a java method) it is not first class and cannot stand on its own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.