Staying Out of Trouble

One thing to keep in mind as you dive into Java interop is that while we can use .method and class/staticMethod in place of functions, they are not functions. They are, instead, special forms, more or less hardwired into Clojure. In particular, you cannot bind a method name:

 ;; Nope. Nope. Nope.
 
 (​def​ count-method .count)

All is not lost, however: you can use the built-in memfn function to turn a method name into a function. For example, while .exists is not a function, (memfn exists) is. This can be useful when you need a function value. If, for instance, you had a collection of File instances:

 (​def​ files [(File. ​"authors.txt"​) (File. ​"titles.txt"​)])

and you needed the parallel collection of Booleans indicating ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.