When, or why, should type hints be avoided?


#1

The clojure.org Java Interop page says “Normally, one should avoid the use of type hints until there is a known performance bottleneck.”

I think that the reason for this is just that you shouldn’t be cluttering up your code with type hint noise unless there’s a good reason for it. Am I wrong? Are there cases in which:

  1. Setting *warn-on-reflection* shows that reflection is occurring that can be avoided with a type hint, but
  2. the offending line is not in performance-critical code, and
  3. there is some harm to including the type hint (other than readability).

i.e. this is a case in which the type hint won’t improve performance. Is it bad to include the type hint (apart from its effect on readability)?

Partly I’m just wondering whether I should take out a series of type hints I added that that turned out not to improve performance (though perhaps some of them could make a difference to performance at a later time when the code changes). The little bit of noise that these type hints add doesn’t bother me.


#2

I’ve wondered myself. I’m using IntelliJ + Cursive, and it’s recently started to give me warnings about e.g. Long/valueOf or similar. I probably misconfigured something, but it sparked the question nonetheless: If I typehint a String, and it’s actually already a Long, does the typehint incur additional cost because it misleads the compiler/…?


#3

Is it bad to include the type hint (apart from its effect on readability)?

No, go for it. My main advice would be to place your type hints strategically in the place where they can do the most good (which is typically in arg lists, then return types, and then in let bindings).

If I typehint a String , and it’s actually already a Long , does the typehint incur additional cost because it misleads the compiler/…?

Generally, no extra cost, it’s a hint and it will just be ignored if the compiler can tell it’s wrong. Caveat on ^long and ^double in signature type hints, which also affect the generated code so if those are wrong, you can run potentially into issues.