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.
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)])))
: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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With