如何在Clojure中使用gen-class定义多个构造函数和状态?
我没有看到一种使用单值映射来定义::init、:state和:constructors的方式。
多个构造函数
如果要在生成的类中具有多个构造函数,您需要在gen-class的:constructors选项中指定所有构造函数参数,并且:init函数应该是多元的以匹配。例如以下内容:
(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}]))
在这种情况下,两个构造函数都将调用相同的零参数超类型构造函数,由构造函数哈希映射中的空向量值指定。
多状态
状态通常是一个哈希映射,因此您不需要多个状态。只需在对象中使用字段名称处使用关键字即可。
{:name "name1"
:special false}
(defn -method1 [this] (:name (.state this)))