Clojure several constructors using the gen class

How to define multiple constructors and states using a gen class in clojure? I see no way to do this with unambiguous mappings for: init ,: state and: constructors.

+6
source share
1 answer

Several designers

To have several constructors in the generated class, you need all the constructor parameters specified in the option: gen class constructors, and the init function must be multi-valued 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 will call the same constructor of the supertype of the null parameter, as defined by the empty vector value in the hash map of the constructor:

Multiple states

A state is usually a hash map, so you do not need multiple states. Just use keywords in which you would use the field names in the object.

 {:name "name1" :special false} (defn -method1 [this] (:name (.state this))) 
+10
source

Source: https://habr.com/ru/post/953753/


All Articles