How to specify the possibility of two types to a variable?
(defn connect! [(or ^:String :^java.net.InetAddress) host ^:Integer port] ...)
Thanks!
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.