簡體   English   中英

在Clojure中輸入函數的提示

[英]Type hinting for functions in Clojure

我正在嘗試解決Clojure中的反射警告,這似乎是由於缺少對普通Java對象的函數返回值的類型推斷。

演示此問題的簡單示例代碼:

(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

解決這個問題的最佳方法是什么? 這可以用類型提示完成嗎?

這兩個版本似乎有效:

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

請注意,類型提示在Clojure中仍然有點不穩定,現在導致1.2版本,所以這可能永遠不會以相同的方式工作。 另請注意, #^已棄用,而有利於^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM