问题描述
您可以在协议中提示返回类型
You can hint a return type in a protocol
(defprotocol Individual
(^Integer age [this]))
,编译器将使你的方法符合:
and the compiler will make your methods comply:
(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 don't have to honour the type-hint:
(defrecord person []
Individual
(age [this] "one"))
(age (new person))
; "one"
类型提示是否有效果?
Does the type-hint have any effect?
这是后续
推荐答案
返回类型提示转到协议函数 age
作为标记。从那里,标签在本地类型推理中使用。要观察此操作:
The return type hint goes to the protocol function age
as tag. From there, the tag is used in local type inference. To observe this in action:
- (.longValue(age(new person)))
ClassCastException java。 lang.String不能转换为java.lang.Integer
net.bendlas.lintox / eval18038(form-init4752901931682060526.clj:1)
;; longValue是一个Integer的方法,所以已经插入了一个直接转型
如果类型提示已关闭,如果你调用的方法不是在提示类型,编译器插入一个(慢)调用到反射器,而不是简单的转型:
If the type hint had been left off, or if you call a method not on the hinted type, the compiler inserts a (slow) call into the reflector, instead of the plain cast:
- (.otherMethod(age(new person)))
IllegalArgumentException找不到匹配字段:java.lang.String类的otherMethod clojure.lang.Reflector.getInstanceField(Reflector.java:271)
这篇关于在协议中提示返回类型在Clojure中有什么影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!