Are there hints of return types in protocols in Clojure?

You can specify the type of return in the protocol

(defprotocol Individual (^Integer age [this])) 

and the compiler will execute your methods:

 (defrecord person [] Individual (^String age [this] "one")) ; CompilerException java.lang.IllegalArgumentException: Mismatched return type: age, expected: java.lang.Object, had: java.lang.String, ... 

But you do not need to follow a hint like:

 (defrecord person [] Individual (age [this] "one")) (age (new person)) ; "one" 

Does the hint type have any effect?


This continuation Is it possible to specify the type of the returned method in clojure defrecord?

+7
clojure
source share
1 answer

The return type of the hint goes to the age protocol function as a tag. From there, the tag is used to output the local type. To watch this in action:

- (.longValue (age (new person))) ClassCastException java.lang.String cannot be cast to java.lang.Integer net.bendlas.lintox/eval18038 (form-init4752901931682060526.clj:1) ;; longValue is a method of Integer, so a direct cast has been inserted

If the type hint was stopped, or you call the method not according to the intended type, the compiler inserts a (slow) call into the reflector instead of the usual press:

- (.otherMethod (age (new person))) IllegalArgumentException No matching field found: otherMethod for class java.lang.String clojure.lang.Reflector.getInstanceField (Reflector.java:271)

+3
source share

All Articles