When and where d开发者_开发问答o you put type annotations in Clojure code? Obviously when performance counts. But are there rules by which you can live of when (only when doing Java Interop?) and where to add them (function definition arguments)?
The overriding reason that I"m aware of is performance. Type hinting in clojure removes reflection, which can slow down performance. So I would put type hints in functions which I've measured to be performance critical.
There is a description in the java interop section at clojure.org. Among the remarks:
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.
... Once a type hint has been placed on an identifier or expression, the compiler will try to resolve any calls to methods thereupon at compile time. In addition, the compiler will track the use of any return values and infer types for their use and so on, so very few hints are needed to get a fully compile-time resolved series of calls. Note that type hints are not needed for static members (or their return values!) as the compiler always has the type for statics.
You can always turn on the warn on reflection flag to see where reflection is being called, and consequently, where type hints might help.
EDIT:
Regarding your question "Only for java interop?" --no. Type hints will be useful even in a pure clojure application. The issue of reflection slowing down performance is a fact of life on the JVM, and is an issue that dynamic languages have to deal with in general.
Regarding where type hints can be placed, from clojure.org:
They can be placed on function parameters, let-bound names, var names (when defined), and expressions:
I know you already accepted an answer and this is not a direct answer to your question, but Lau just posted a really nice article on Functional Fluid Dynamics in Clojure which is quite educational when it comes to type-hinting for performance reasons.
精彩评论