Hakan Özler
Hakan Özler

Reputation: 988

Casting issue: java.lang.Number to gt Clojure

I recently receive the error which is "ClassCastException clojure.core$num cannot be cast to java.lang.Number clojure.lang.Numbers.gt" .

My implemented function called "getNumber" only gets an integer number.

Here is the my function called getLoop returns this error:

 (defn getLoop []
    (getNumber num)
    (loop [z num]
           (when (> z -1)
           (println z)
           (recur (- z 1)))))

On the one hand, this query works correctly.

 (defn getLoop []
    (loop [z 3]
           (when (> z -1)
           (println z)
           (recur (- z 1)))))

I am wondering how I can avoid the error in the "getLoop" function?

Thanks in advance!

Upvotes: 0

Views: 1584

Answers (2)

jbm
jbm

Reputation: 2600

The num in getLoop, and thus z, are referring to clojure.core/num, which is a function that coerces its argument to a number. That's why the exception says "clojure.core$num cannot be cast to java.lang.Number" - it's saying that the function num is being used in place of a number and that this isn't supported. This is happening because there's nothing in getLoop that would bind num to a different value.

I think you mean one of two possibilities:

;; First possibility
(defn getLoop [num]
  (loop [z num]
    (when (> z -1)
      (println z)
      (recur (- z 1)))))

;; Usage:
(getLoop (getNumber num))
;; Or:
(-> num getNumber getLoop)

;; Second possibility
(defn getLoop [num]
  (let [num (getNumber num)]
    (loop [z num]
      (when (> z -1)
        (println z)
        (recur (- z 1))))))

;; Usage:
(getLoop num) ;; (It calls `getNumber` internally)

Upvotes: 0

Leon Grapenthin
Leon Grapenthin

Reputation: 9276

The symbol num is not bound to the return value of (getNumber num) in your function body. Here is the function in more idiomatic Clojure:

(defn getLoop [num]
  (loop [n num]
    (when-not (zero? n)
      (println n)
      (recur (dec n)))))

If your getNumber returns a number as you said, it should be invokable like this:

(-> num getNumber getLoop)

Upvotes: 0

Related Questions