ChrisR
ChrisR

Reputation: 1237

Clojure syntax question re: #^

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.

Upvotes: 11

Views: 304

Answers (2)

mtyaka
mtyaka

Reputation: 8850

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.

Upvotes: 11

Gert
Gert

Reputation: 3859

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

Upvotes: 8

Related Questions