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"])
java function clojure
Mark
source share