Calling Methods
Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (83 / 107)
👈 Calling Out to Java | TOC | Reader Conditionals 👉
Once we have an instance of a class, we can call methods on it. The notation is similar to making a regular function call. When we call a method, we pass the object its first parameter, followed by any other parameters that the method accepts.
(let [f (File. ".")]
(println (.getAbsolutePath f)))
Here we’ve created a new file object f and we’ve called .getAbsolutePath on it. Notice that methods have a period (.) in front of them to differentiate them from regular Clojure functions. If we wanted to call a static function or a variable in a class, we would use the / notation, as follows:
(str File/separator "foo" File/separator "bar")
(Math/sqrt 256)
We can also chain multiple method calls together using the double period (..) notation as our shorthand. Say we wanted to get the string indicating the file path and then get its bytes; we could write the code for that in two ways:
(.getBytes (.getAbsolutePath (File. ".")))
(.. (File. ".") getAbsolutePath getBytes)
The second notation looks more natural and is easier to read. Although there’s other syntactic sugar for working with Java, the preceding is sufficient for following the material we cover in this book.