Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure static typing, part 2

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.

like image 977
Ralph Avatar asked Jun 04 '26 20:06

Ralph


1 Answers

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.

like image 120
levand Avatar answered Jun 08 '26 00:06

levand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!