在Clojure中输入函数提示 [英] Type hinting for functions in Clojure
问题描述
我试图解决Clojure中的反射警告,这似乎是由于缺少对普通Java对象的函数返回值的类型推断而导致的。
平凡示例代码演示了这个问题:
$ p $ (set!* warn-on-reflection * true)
(defn foo [#^ Integer x](+ 3 x))
(.equals(foo 2)(foo 2))
=>反射警告,NO_SOURCE_PATH:10 - 呼叫等于无法解决。
true
解决此问题的最佳方法是什么?这可以通过类型提示完成吗?
这两个版本似乎可以正常工作:
用户> (defn foo [^ Integer x](+ 3 x))
#'user / foo
user> (.equals(foo 2)(foo 2))
反映警告,NO_SOURCE_FILE:1 - 无法解析等于的呼叫。 ;'
true
user> (.equals ^ Integer(foo 2)^ Integer(foo 2))
true
user> (defn ^ Integer foo [^ Integer x](+ 3 x))
#'user / foo
user> (.equals(foo 2)(foo 2))
true
请注意,在Clojure中仍然有点不稳定,直到1.2版本发布,所以这可能永远不会以相同的方式工作。另请注意,#^
已被弃用,以支持 ^
。
I'm trying to resolve a reflection warning in Clojure that seems to result from the lack of type inference on function return values that are normal Java objects.
Trivial example code that demonstrates the issue:
(set! *warn-on-reflection* true)
(defn foo [#^Integer x] (+ 3 x))
(.equals (foo 2) (foo 2))
=> Reflection warning, NO_SOURCE_PATH:10 - call to equals can't be resolved.
true
What is the best way to solve this? Can this be done with type hints?
These two versions appear to work:
user> (defn foo [^Integer x] (+ 3 x))
#'user/foo
user> (.equals (foo 2) (foo 2))
Reflection warning, NO_SOURCE_FILE:1 - call to equals can't be resolved. ;'
true
user> (.equals ^Integer (foo 2) ^Integer (foo 2))
true
user> (defn ^Integer foo [^Integer x] (+ 3 x))
#'user/foo
user> (.equals (foo 2) (foo 2))
true
Note that type hinting is still a bit in flux in Clojure right now leading up to the 1.2 release, so this might not work the same way forever. Note also that #^
is deprecated in favor of ^
.
这篇关于在Clojure中输入函数提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!