How to get an Fn which calls a Java method?

后端 未结 4 1308
梦谈多话
梦谈多话 2021-01-20 22:33

I\'m learning Clojure. I wrote this code to recursively walk a directory.

(tree-seq #(.isDirectory %1) #(.listFiles %1) (File. \"/my-directory\"))

4条回答
  •  情话喂你
    2021-01-20 23:25

    Joost is spot on about Java methods not being first class functions.

    As an approach to dealing with this, I usually like to wrap Java functions in a Clojure function (or find a library that does this already), then it is easy to use them in an idiomatic first-class way:

    (defn directory? [^java.io.File file]
      (.isDirectory file))
    
    (defn list-files [^java.io.File file]
      (.listFiles %1))
    
    (tree-seq directory? list-files (File. "/my-directory"))
    

    This is a few more lines of code, but has the following advantages:

    • You can add type hints in your functions to avoid reflection (as above)
    • The final code is cleaner and more idiomatic
    • You have abstracted away from the underlying Java interop

提交回复
热议问题