您可以在协议中暗示返回类型
(defprotocol Individual
(^Integer age [this]))
并且编译器将使您的方法符合:
(defrecord person []
Individual
(^String age [this] "one"))
; CompilerException java.lang.IllegalArgumentException: Mismatched return type: age, expected: java.lang.Object, had: java.lang.String, ...
但你不必遵守类型提示:
(defrecord person []
Individual
(age [this] "one"))
(age (new person))
; "one"
type-hint 有什么作用吗?
这是后续您可以在 clojure defrecord 中指定方法的返回类型吗? https://stackoverflow.com/questions/22954681/can-you-specify-the-return-type-of-a-method-in-a-clojure-defrecord
返回类型提示转到协议函数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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)