Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure syntax question re: #^

Tags:

clojure

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.

like image 980
ChrisR Avatar asked Jul 11 '11 03:07

ChrisR


2 Answers

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.

like image 105
mtyaka Avatar answered Nov 08 '22 01:11

mtyaka


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

like image 28
Gert Avatar answered Nov 08 '22 01:11

Gert