协议中的提示返回类型是否在Clojure中有任何影响?

时间:2014-04-09 13:22:13

标签: clojure

您可以在协议中提示返回类型

(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"

类型提示有效吗?


这是Can you specify the return type of a method in a clojure defrecord?

的后续行动

1 个答案:

答案 0 :(得分:3)

返回类型提示作为标记转到协议函数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)