Multimethod Cannot invoke "Object.getClass()" because "x" is null

Hello community,

I’ve started learning Clojure and I’m trying to create a multimethod. What I’m doing is
(defn dispatch-published [book]
(cond
(string? book) :string-book
(< (:published book) 1928) :public-domain
(< (:published book) 1978) :old-copyright
:else :new-copyright))

(defmulti compute-royalties dispatch-published)

(defmethod compute-royalties :public-domain [book] 0)

(defmethod compute-royalties :old-copyright [book]
  ;; Compute royalties based on old copyright law.
  )
(defmethod compute-royalties :new-copyright [book]
  ;; Compute royalties based on new copyright law.
)

(defmethod compute-royalties :string-book [book]
book)

I call it like that with the string value
(compute-royalties “Hello”)

than I get an error

Execution error (NullPointerException) at learning-1.core/dispatch-published (form-init6630949825203615092.clj:3).
Cannot invoke “Object.getClass()” because “x” is null

I don’t understand why it happens. Any help will be much appreciated. According to error text this happens in function dispatch-published when doing (string? book) :string-book but can’t understand why. “Hello” so I expect dispatch-published to return :string-book. The defmethod

(defmethod compute-royalties :string-book [book]
book)

should give me back “Hello”. Am I Mixing up something? Thank you in advance.

1 Like

I pasted your code into a fresh Clojure REPL and it worked.

Can you explain a bit more about how you are running the code, which version of Clojure you are using etc.?

Did you change the definitions of any of the pieces and forget to re-evaluate the code, i.e., maybe you have stale state in your REPL?

The full exception with the stacktrace would be available via *e in the REPL so that might give you more information on exactly what operation is failing.

3 Likes

Hello.

I restarted REPL and it began working fine. Not sure why this happened. Thanks for your answer.

1 Like