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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With