Welcome! Please see the About page for a little more info on how this works.

0 votes
in Java Interop by
edited by

I often find myself addressing reflection warnings by placing annotations which type is completely obvious:

(def ^String foo "bar") ;; adding ^String fixes reflection warnings elsewhere

"bar" is a String, that is unmistakably known at compile-time, so it seems to me that I'm doing grunt work, and also creating something that might become outdated later.

Has it been considered to add "type inference" for such straightforward cases?

("type inference" is probably an exaggerated term for this use case)

...I can imagine at least one objection: (def ^CharSequence foo "bar") can also be accurate and useful. But a good default would be to infer the type of x to be the x's class - if a user wanted to annotate x as one of its ancestors (here: CharSequence, Object), he could override the inferred default by hand.

1 Answer

+1 vote
by

(def foo "bar") creates a Clojure var - technically a mutable form of storage.

There is no guarantee (implicit or explicit) that the code won't do something like (alter-var-root #'foo #(do % 42)) unless someone provides hints. That would make it difficult to do implicit type inference in the core language.

by
I considered that, and alter-var-root could simply erase any type annotations if the current one was inferred, instead of programmer-specified (a distinction that would seem easy via an additional piece of metadata.)
by
Erasing a type hint via the use of a runtime action in alter-var-root doesn't help code that has already been compiled with the original type information.
by
One can also can observe that code can be broken in many ways if one reloads code in an unstructured way (regardless of chosen workflow) and/or uses low-level APIs.

Perhaps this feature could be controlled by e.g. a dynamic var or System property, for those of us who care (and won't hack-load code)
by
We're certainly not opposed to adding type inference when possible but this particular change is non-trivial and not likely to gain traction in light of the effectiveness of type hinting. That said, the Typed Clojure project may have a satisfactory solution for this scenario and it might be worth exploring. https://typedclojure.org
...