【问题标题】:Scope of type hints in Clojure?Clojure 中类型提示的范围?
【发布时间】:2013-08-01 22:27:59
【问题描述】:

我正在寻找有关 Clojure 中类型提示范围的信息,例如,如果我写了

(defn big-add [^BigInteger x y] (.add x y))

是一样的

(defn big-add [^BigInteger x ^BigInteger y] (.add x y))

?假设我写

(defn big-sum 
  ([] BigInteger/ZERO)
  ([^BigInteger x] x)
  ([^BigInteger x & more] (.add x (apply big-sum more) )))

Clojure 是否假定more 中充满了BigInteger?假设我不想告诉它?我会做类似的事情吗

(defn foo [^BigInteger x & ^Long more] ...)

【问题讨论】:

    标签: clojure clojure-java-interop


    【解决方案1】:

    只需将 warn-on-reflection 设置为 true 并使用无法解析类型的函数测试您的表达式。

    REPL:

    (set! *warn-on-reflection* true)
    (defn testo [s]
          (str s))
    => #'user/testo
    
    (defn testo [s]
          (.charAt s 1))
    => Reflection warning, NO_SOURCE_PATH:2:8 - call to charAt can't be resolved.
    
    (defn testo [^java.lang.String s]
          (.charAt s 1))
    => #'user/testo
    
    (defn testo [^java.lang.String s s2]
          (.charAt s2 1))
    => Reflection warning, NO_SOURCE_PATH:2:8 - call to charAt can't be resolved.
    
    (defn testo [^java.lang.String s & more]
          (.charAt (first more) 1))
    => Reflection warning, NO_SOURCE_PATH:2:8 - call to charAt can't be resolved.
    

    最后

    (defn testo [s & ^java.lang.String more]
          (.charAt (first more) 1))
    => CompilerException java.lang.RuntimeException: & arg cannot have type hint, compiling:(NO_SOURCE_PATH:1:1) 
    

    您的每个问题的简短答案都是“否”:(

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 2017-07-27
      • 2011-03-02
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多