在 cond 语句的表达式中调用 str 函数导致 ClassCastException

Calling str function in the expression in a cond statement cause a ClassCastException

如果我设置 cond,其中匹配分支中的表达式调用 (str),我会得到 ClassCastException。但是,如果我将 str 更改为 format,问题就会消失。

代码:

(defn begins-with [chr str]
  (cond 
    (or (nil? str) (empty? str)) "Hey the string is empty!"
    (= (first str) chr) (str "found: " chr)
    :else "Didn't begin with the target char"))

REPL:

(begins-with \A "")
=> "Hey the string is empty!"

(begins-with \A "asdf")
=> "Didn't begin with the target char"

(begins-with \A "Apple")
ClassCastException java.lang.String cannot be cast to clojure.lang.IFn  user/begins-with (form-init5132500100026084016.clj:4)

但是,如果我将表达式中的 str 换成 format 一切正常

更新代码

(defn begins-with [chr str]
  (cond 
    (or (nil? str) (empty? str)) "Hey the string is empty!"
    (= (first str) chr) (format "found: %s" chr)
    :else "Didn't begin with the target char"))

REPL:

(begins-with \A "Apple")
=> "found: A"

突然好用了!!

谁能解释一下这种行为?我错过了一些明显的东西吗?

您的参数称为 str,因此它隐藏了核心 str 函数。

(str "found: " chr)因此被计算为("Apple" "found: " \A),这是行不通的。重命名您的变量以修复它。