Question

This is a follow-up to my previous question on Clojure static typing.

I browsed the Java source code for the compiler and there are several places where it checks the value of *warn-on-reflection*, but when I compile the following code, I only get a run-time error:

(defn div-2 [^String s] (/ 2 s))

Are there any circumstances where this code should not give a compile-time warning (it does not)? How difficult would it be to have the compiler give a warning on the following code:

(defn get-length [^String s] (.length s))
(defn test-get-length [] (get-length 2.0))

Thanks.

Was it helpful?

Solution

The problem is that the compiler doesn't track the type of def'd vars. So yes, in your simple example, it would be possible. But how often do you pass a literal? Rarely, in a real program.

Making types "flow through" like they do in a real statically typed language would require an extensive amount of reworking. You'd have to track type information through vars, dynamically rebound vars, dereferences, etc. And then you still have the issue of pulling items out of collections/sequences, which implies genericized types, which is a huge can of worms...

Type annotations in Clojure were never intended to provide type-safety at compile time - they just allow the compiler to generate more optimized code (at the expense of a run-time error if an unexpected type is encountered.)

Instrumenting the compiler with full static typing information might be possible, but at that point you've largely rewritten the language, and you'll have had to make many decisions and tradeoffs in how types are handled. It really wouldn't be Clojure anymore.

OTHER TIPS

Rather than trying to modify the compiler, why not write a separate tool that just scans a Clojure code file and warns about type violations? You could develop your own type notation using macros that just collapse into normal untyped Clojure code. But when you run the static type checker, it would grok the types and output warnings.

If you were up for a slightly bigger challenge, you could even have it perform type inference thus lowering the burden of notation.

Following up that thread, there is now a project aiming at bringing gradual typing into clojure (like Dart, etc.). Worth testing it : Typed-Clojure

If someone can also give some feedback after real use...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top