Clojure: def for java static function

Consider the following Clojure code:

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

Everything is fine. But obviously this is just a different name and meaningless style refactoring:

 (def space? Character/isWhitespace) 

But I get a compilation error:

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

Why can't he find him? It works great with Clojure features:

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

What's going on here? Why does def not work with a static Java function?

+4
source share
1 answer

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

 (def space? Character/isWhitespace) 

... Clojure is trying to look for a static field (not a method) called isWhitespace in java.lang.Character . Of course, there is no such field, so you get a compilation error.

Other correct ways to rewrite the following statement ...

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

... will be:

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

Edit

Just to add, I believe that the reason Clojure allows (def wrap-space? space?) that there is no ambiguity about what space? . On the other hand, the Java static method may be overloaded with different sets of parameters or may share the same name with a static field. Therefore, for the Java static method alias, you need to clearly indicate which method / field you are using.

+7
source

Source: https://habr.com/ru/post/1500216/


All Articles