Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defrecord Class Not Found Exception

Tags:

clojure

I have two files knapsack.clj and core.clj.

There is defrecord Item in knapsack.clj. I want to use it in core.clj but it is giving me error in cider-repl of java.lang.ClassNotFoundException: discrete-optimization.knapsack.Item even though i have require for the knapsack namespace.

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 is 1.5.1

Solution : For portable solution :

use ->KS/item when referring to item outside of namespace.

like image 875
Ashish Negi Avatar asked Sep 12 '26 11:09

Ashish Negi


2 Answers

While the answer from xsc is not wrong, my preference is to use the constructor functions that are generated from defrecord and avoiding the Java constructor and Java import -isms. 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)])))
like image 127
Alex Miller Avatar answered Sep 15 '26 08:09

Alex Miller


:import references a Java class - and when creating package/class names for those the Clojure compiler converts dashes to underscores. This might thus work:

(:import [discrete_optimization.knapsack Item])
like image 29
xsc Avatar answered Sep 15 '26 07:09

xsc