Defrecord Class not found Exception

I have two files knapsack.clj

and core.clj

.

There knapsack.clj

is defrecord Item

. I want to use it in core.clj but it gives me an error in cider-repl

from java.lang.ClassNotFoundException: discrete-optimization.knapsack.Item

even though I have one require

for the namespace knapsack

.

The code is here:

;; ---- knapsack.clj ---------
(ns discrete-optimization.knapsack)
;; Item record has weight and value of the Item
(defrecord Item
    [weight value])


;; ---- core.clj --------
(ns discrete-optimization.core
  (:require [discrete-optimization.knapsack :as KS])
  (:import [discrete-optimization.knapsack Item]))

;; doing some knapsack in here.. :)
(and 
 (= 5 (KS/knapsack-value 5 [(Item. 3 5)]))
 (= 5 (KS/knapsack-value 5 [(Item. 3 3) (Item. 2 2)])))

      

My clojure version 1.5.1

Solution : For a portable solution:

use ->KS/item

when referring to item

outside the namespace.

+3


source to share


2 answers


While the answer from xsc is not correct, I prefer to use the constructor functions generated from defrecord and avoid Java constructors and Java imports. This is likely to be more portable over time / platforms.



;; ---- knapsack.clj ---------
(ns discrete-optimization.knapsack)
;; Item record has weight and value of the Item
(defrecord Item      
    [weight value])  
;; The ->Item constructor is generated automatically

;; ---- core.clj --------
(ns discrete-optimization.core
  (:require [discrete-optimization.knapsack :as KS]))

;; doing some knapsack in here.. :)
(and 
 (= 5 (KS/knapsack-value 5 [(KS/->Item 3 5)]))
 (= 5 (KS/knapsack-value 5 [(KS/->Item 3 3) (KS/->Item 2 2)])))

      

+3


source


:import

refers to a Java class - and when generating package / class names for those Clojure compiler converts dashes to underscores. This might work:



(:import [discrete_optimization.knapsack Item])

      

+2


source







All Articles