Clojure syntax question re: #^

巧了我就是萌 提交于 2019-12-30 17:24:11

问题


in Rich Hickeys ant game, he has the following code:

(import 
 '(java.awt Color Graphics Dimension)
 '(java.awt.image BufferedImage)
 '(javax.swing JPanel JFrame))

(defn fill-cell [#^Graphics g x y c]
  (doto g
    (.setColor c)
    (.fillRect (* x scale) (* y scale) scale scale)))

I can't find documentation anywhere for what #^ means in this context, any help appreciated.


回答1:


The #^ is the old syntax for metadata reader macro. The syntax has changed to ^ in clojure 1.2. See http://clojure.org/reader. In your example, #^Graphics represents a type hint which is used for performance reasons.




回答2:


The #^ is a "type hint" - it tells Clojure what class the argument will be. In recent versions of clojure you can just say ^Graphics instead of #^Graphics. See Clojure Java Interop - Type Hints for more. A quote from that site:

Clojure supports the use of type hints to assist the compiler in avoiding reflection in performance-critical areas of code. Normally, one should avoid the use of type hints until there is a known performance bottleneck. Type hints are metadata tags placed on symbols or expressions that are consumed by the compiler. They can be placed on function parameters, let-bound names, var names (when defined), and expressions



来源:https://stackoverflow.com/questions/6645514/clojure-syntax-question-re

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!