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

时间:2017-10-01 00:13:57

标签: clojure clojurescript

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

代码:

format

REPL:

(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"))

但是,如果我将表达式中的(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

REPL:

(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"))

它突然起作用!!

任何人都可以解释这种行为吗?我错过了一些明显的东西吗

1 个答案:

答案 0 :(得分:3)

你的论点被称为str,因此它影响核心str函数。

因此,

(str "found: " chr)被评估为("Apple" "found: " \A),但这不起作用。重命名变量以修复它。