leontalbot
leontalbot

Reputation: 2543

Clojure: multiple type hints?

How to specify the possibility of two types to a variable?

(defn connect! [(or ^:String :^java.net.InetAddress) host ^:Integer port] ...)

Thanks!

Upvotes: 1

Views: 762

Answers (2)

Alex
Alex

Reputation: 13941

From the Clojure documentation:

Clojure supports the use of type hints to assist the compiler in avoiding reflection in performance-critical areas of code. Normally, one should avoid the use of type hints until there is a known performance bottleneck

The purpose of type hints is to allow the compiler to avoid reflection. Any self-documentation aspects of type-hinted code are secondary. When you say the following:

(defn connect! [^String host])

What you're telling the compiler is to resolve all Java interop method calls on host at compile time to method calls on the String class. Allowing a form to be hinted with multiple classes would defeat this purpose - the compiler wouldn't know which class to compile a method call as. Even if it did, an object cannot be a String and an InetAddress at the same time, so any method calls compiled against the String class would be guaranteed to fail with a ClassCastException if an InetAddress happened to be passed in, and vice versa.

Upvotes: 3

Lee
Lee

Reputation: 144136

As far as I know the only way is to do the check yourself and add the hint inside a let:

(condp instance? host
  String (let [^String s] (...))
  InetAddress (let [^InetAddress a] (...)))

Upvotes: 1

Related Questions