What does -> do in clojure?

前端 未结 6 1288
既然无缘
既然无缘 2021-02-01 04:02

I have seen the clojure symbol -> used in many places, but I am unsure as to what this symbol is called and does, or even whether it is part of standard clojure. Could someone e

6条回答
  •  有刺的猬
    2021-02-01 05:06

    '->' is a macro. The best way to describe it, I think, is in the example of the "dot special form" for which it serves the purpose of making the code more terse and legible as is indicated on the clojure.org website's explanation of the The Dot special form

    (.. System (getProperties) (get "os.name"))
    

    expands to:

    (. (. System (getProperties)) (get "os.name"))
    

    but is easier to write, read, and understand. See also the -> macro which can be used similarly:

    (-> (System/getProperties) (.get "os.name"))
    

    There is also 'doto'. Let's say you have a single object on which you'd like to call several consecutive setters. You could use 'doto'.

    (doto person
      (.setFName "Joe")
      (.setLName "Bob")
      (.setHeight [6 2]))
    

    In the above example the setters don't return anything, making 'doto' the appropriate choice. The -> would not work in place of 'doto' unless the setters returned 'this'.

    So, those are some techniques related to the -> macro. I hope that helps explain not only what they do, but also why they exist.

提交回复
热议问题