Rory O'Kane
Rory O'Kane

Reputation: 30428

ClassCastException: java.lang.Boolean cannot be cast to clojure.lang.IFn

A question that a Stack Overflow user emailed to me:

I have the below function:

(defn partial-or-fill-at-test? [price]
  (if (partial-or-fill-at? price) true (do (println "WRONG PRICE") false)))

I get the below error when I use it:

java.lang.ClassCastException: java.lang.Boolean cannot be cast to clojure.lang.IFn

I want to it to print something when the result of that predicate is false. Any help will do.

Upvotes: 1

Views: 1884

Answers (1)

Rory O'Kane
Rory O'Kane

Reputation: 30428

The problem is somewhere in your definition of partial-or-fill-at?. If I try a simple definition of partial-or-fill-at? as as function, everything works:

(defn partial-or-fill-at? [price] (> price 100))

(defn partial-or-fill-at-test? [price]
  (if (partial-or-fill-at? price) true (do (println "WRONG PRICE") false)))
user=> (partial-or-fill-at-test? 200)
true
user=> (partial-or-fill-at-test? 50)
WRONG PRICE
false

The error message java.lang.Boolean cannot be cast to clojure.lang.IFn means that somewhere, you have a Boolean (true or false) that is trying to used as an IFn (Clojure’s name for a function).

The true and false literals in your code are being used as values, not functions, so that is not the problem. The only place where a boolean could be used like a function is partial-or-fill-at?. If you defined it with a boolean value, using def instead of defn, you would get this error. For example, perhaps you accidentally wrote this:

; earlier in the code
(def price 500)

; …

(def partial-or-fill-at? (> price 100))

when you meant this:

(defn partial-or-fill-at? [price] (> price 100))

Inspect your definition of partial-or-fill-at? – also making sure that all parentheses balance and that the definition covers the section of code you expect it to – and figure out how to change its value from a boolean to a function.

Upvotes: 1

Related Questions