开发者

Type hinting for functions in Clojure

开发者 https://www.devze.com 2023-01-02 21:16 出处:网络
I\'m trying to resolve a reflection warning in Clojure that seems to result from th开发者_开发技巧e lack of type inference on function return values that are normal Java objects.

I'm trying to resolve a reflection warning in Clojure that seems to result from th开发者_开发技巧e 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 ^.

0

精彩评论

暂无评论...
验证码 换一张
取 消