您可以在协议中提示返回类型
(defprotocol Individual
(^Integer age [this]))
Run Code Online (Sandbox Code Playgroud)
并且编译器将使您的方法符合:
(defrecord person []
Individual
(^String age [this] "one"))
; CompilerException java.lang.IllegalArgumentException: Mismatched return type: age, expected: java.lang.Object, had: java.lang.String, ...
Run Code Online (Sandbox Code Playgroud)
但是您不必遵守类型提示:
(defrecord person []
Individual
(age [this] "one"))
(age (new person))
; "one"
Run Code Online (Sandbox Code Playgroud)
类型提示有效吗?
返回类型提示age作为标记发送到协议函数。从那里,该标签用于本地类型推断。要观察其实际情况:
- (.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
如果类型提示已关闭,或者如果您调用的方法不在提示类型上,则编译器会在反射器中插入一个(缓慢的)调用,而不是普通的强制转换:
- (.otherMethod (age (new person)))
IllegalArgumentException No matching field found: otherMethod for class java.lang.String clojure.lang.Reflector.getInstanceField (Reflector.java:271)