You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在->宏中为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->部分提取为变量的前提下添加有效的类型提示?

解决方法

可以通过两种方式实现:

  1. 直接在方法调用时标注对象类型
    Clojure支持在实例方法调用时,直接为目标对象添加类型提示,这种方式不受cond->宏展开的影响,能让编译器明确识别对象类型,消除反射警告:

    (defn test1 [x]
      (-> x
          (cond-> (int? x) make-it-a-string-please)
          (.getBytes ^String)))
    
  2. 用identity中转添加类型提示
    通过无副作用的identity函数做一次中转,为其添加类型提示,同样能让编译器认定后续对象为String类型:

    (defn test1 [x]
      (-> x
          (cond-> (int? x) make-it-a-string-please)
          ^String identity
          (.getBytes)))
    

内容的提问来源于stack exchange,提问作者kamituel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 17:35:02