2017-10-01 44 views
0

如果我设置了一个cond,其中匹配分支中的表达式调用(str),我得到ClassCastException。但是,如果我将str更改为format,问题就会消失。在cond语句的表达式中调用str函数导致ClassCastException

代码:

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

这突然的作品!

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

回答

3

你的论点叫str,所以它的核心功能是str。因此评估为("Apple" "found: " \A),其不起作用。重命名你的变量来修复它。