Search code examples
clojurecursive

How to disambiguate in Clojure


I have this function in a namespace that does not import/require/use any other packages:

(defn crash [msg]
  (throw (Throwable. msg)))

Cursive (the IntelliJ IDEA IDE Plugin) highlights Throwable and gives me the message Cannot disambiguate overloads of Throwable. I get the same message with Exception and Error.

I don't understand the source of this message - I doubt that these Java classes are defined in any other jar files apart from the Java language ones. Anything I can to make this message go away?

These are in the project.clj:

  :dependencies [[org.clojure/clojure "1.6.0"]
                 [net.mikera/imagez "0.8.0"]
                 [org.clojure/math.numeric-tower "0.0.4"]]

Solution

  • Throwable has two 1-arg constructors (doc): one expecting a String and the other expecting a Throwable.

    At runtime Clojure figures it out (since, in this specific case, it's impossible for an object to be both a String and a Throwable) but this requires the use of reflection.

    Adding a type-hint to msg to specify which overload you expect to use would remove the need for reflection and hopefully calms Cursive down.

    (defn crash [^String msg]
      (throw (Throwable. msg)))