How to disambiguate in Clojure
Asked Answered
C

1

9

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"]]
Commination answered 9/9, 2015 at 7:1 Comment(0)
S
12

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)))
Spiniferous answered 9/9, 2015 at 7:33 Comment(3)
Both the diagnosis and the solution are correct here - I should probably make that message friendlier. Cursive tries to warn whenever interop will require reflection using the same logic as the compiler.Sumner
@Sumner could you list the candidate overloads?Spiniferous
Yes, I tried that but the tooltips occasionally got extremely large. I'll try it again and see if I can work around that.Sumner

© 2022 - 2024 — McMap. All rights reserved.