如何在->宏中为cond->添加类型提示以消除反射警告?
问题描述
以下Clojure代码中,.getBytes调用会产生两个反射警告:
(defn make-it-a-string-please [x] (str x)) (defn test1 [x] (-> x (cond-> (int? x) make-it-a-string-please) (.getBytes))) (defn test2 [x] (-> x (make-it-a-string-please) (.getBytes)))
为test2添加类型提示后可消除警告:
(defn test2 [x] (-> x ^String (make-it-a-string-please) (.getBytes)))
但为test1中的cond->添加同样的类型提示却无效:
(defn test1 [x] (-> x ^String (cond-> (int? x) make-it-a-string-please) (.getBytes)))
请问能否在不修改make-it-a-string-please函数、不将cond->部分提取为变量的前提下添加有效的类型提示?
解决方法
可以通过两种方式实现:
直接在方法调用时标注对象类型
Clojure支持在实例方法调用时,直接为目标对象添加类型提示,这种方式不受cond->宏展开的影响,能让编译器明确识别对象类型,消除反射警告:(defn test1 [x] (-> x (cond-> (int? x) make-it-a-string-please) (.getBytes ^String)))用
identity中转添加类型提示
通过无副作用的identity函数做一次中转,为其添加类型提示,同样能让编译器认定后续对象为String类型:(defn test1 [x] (-> x (cond-> (int? x) make-it-a-string-please) ^String identity (.getBytes)))
内容的提问来源于stack exchange,提问作者kamituel
相关产品推荐
相关产品推荐

