clojure gen-class generated classes invocation issue

166 views Asked by At

I defined the following MyCache.clj

(ns abcd.MyCache
  (:gen-class
   :name "abcd.MyCache"
   :init "init"
   :constructors { [java.text.DateFormat][] }
   :methods [ [now [] void] [myformat [long] String] ]
   :state "state"
   :main false))

(defn -init[format]
  ([[] (atom {:format format})]))



(defn -now[this] ( (:format @(.state this)) (System/currentTimeMillis)))

(defn -myformat[this time]
    ( (:format @(.state this) (new java.util.Date time))))

I compiled the above file using (compile 'abcd.MyCache) successfully.

When I am trying to use the generated classes as shown below..I am getting errors. Please help.

user=> (new abcd.MyCache (new java.text.SimpleDateFormat "mmDDyyyy"))
IllegalArgumentException Key must be integer  clojure.lang.APersistentVector.invoke (APersistentVector.java:265)
1

There are 1 answers

3
Chiron On BEST ANSWER

I don't feel well about this:

(defn -init[format]
  ([] [atom {:format format}]))

You are trying to get an element from a vector and it is expects an index (number).

What is correct is to deref the atom and get its value as the index of the vector. But again in your case, you are trying to query an empty vector.

Notice also, that [atom {:format format}] isn't the correct way to create an atom. You should use:

(atom {:format format})

And by the way, the following form is the preferred one to create Java objects (nothing wrong with (new) of course):

(Date.)
(DateFormat.)