Clojure multiple constructors using gen-class
Asked Answered
C

1

8

How can i define multiple constructors and states using gen-class in clojure? I do not see a way to do this with single valued mappings for :init, :state and :constructors.

Celloidin answered 13/9, 2013 at 6:55 Comment(0)
A
13

Multiple Constructors

To have multiple constructors on the generated class you need all the constructor parameters specified in the :constructors option of gen-class, and the :init function should be multi-arity to match. Something like the following:

(ns something-amazing
  (:gen-class :init myconstructor
              :state state
              :constructors {[String] []
                             [String String] []}))

(defn -myconstructor
  ([^String p1] [[] {:name p1 :special false}])
  ([^String p1 ^String p2] [[] {:name p1 :special p2}]))

In this case, both constructors would call the same zero-parameter super-type constructor, as specified by the empty vector values in the :constructor hash-map.

Multiple States

State is generally a hash-map, so you don't need multiple states. Just use keywords where you would use field names in an object.

{:name "name1"
 :special false}

(defn -method1 [this] (:name (.state this)))
Aliciaalick answered 13/9, 2013 at 8:0 Comment(2)
awesome! Thanks. plain clojure concepts of maps and multi artiy functions makes this so easy.:)Celloidin
If your constructor type is not AOT-compiled but your gen-class is, you'll get an error at compilation time about the class not being found. Replacing the specialized type w/ Object in :constructors will get around this.Alundum

© 2022 - 2024 — McMap. All rights reserved.