Library Functions and Java Methods in Clojure

When reading Clojure Programming, I noticed that there are alternative ways to do some operations in Clojure. For example, let's say we need to convert all the characters in a string to their uppercase variants.

We can use .toUpperCase :

 user> (.toUpperCase "foo") ;; => "FOO" 

Just like clojure.string/upper-case :

 user> (clojure.string/upper-case "foo") ;; => "FOO" 

So far, clojure.string/upper-case is a function, and we can consider it as such:

 user> (map clojure.string/upper-case ["foo" "bar" "baz"]) ;; => ("FOO" "BAR" "BAZ") 

... we cannot do the same with .toUpperCase :

 user> (map .toUpperCase ["foo" "bar" "baz"]) CompilerException java.lang.RuntimeException: Unable to resolve symbol... 

I assume .toUpperCase is a direct call to the Java method, and Clojure knows how to deal with this symbol when it is the first element of the form.

Q : what should I use .toUpperCase or clojure.string/upper-case and what is the difference between:

 (map clojure.string/upper-case ["foo" "bar" "baz"]) 

and

 (map (fn [x] (.toUpperCase x)) ["foo" "bar" "baz"]) 
+7
java function clojure
source share
2 answers

Either works: this is basically a compromise:

Benefits of Clojure wrapped features:

  • The more idiomatic style of Clojure
  • It will most likely be portable (e.g. ClojureScript)
  • Can be passed to higher order functions

Benefits of using Java methods:

  • Slightly improved performance (if you use type hints correctly to avoid reflection)
  • More transparent if you work with Java programmers / Java base codes.

I usually prefer to use wrapped Clojure functions, unless I tested and found a performance issue, after which I could go down to direct the Java interaction.

+7
source share

clojure.string/upper-case is just a wrapper function of the java.lang.String.toUpperCase method. You can register in your replica.

 user=> (source clojure.string/upper-case) (defn ^String upper-case "Converts string to all upper-case." {:added "1.2"} [^CharSequence s] (.. s toString toUpperCase)) 

As you can see, upper-case just call toUpperCase .

I do not think that there is a strong rule to choose only one of them. However, as you already know, the .toUpperCase method .toUpperCase not a clojure function and cannot be passed as an argument to other higher-order functions. Thus, it would be better to use clojure.string/upper-case if you have no particular reason to use the .toUpperCase method.

+6
source share

All Articles