简体   繁体   English

Clojure使用gen-class的多个构造函数

[英]Clojure multiple constructors using gen-class

How can i define multiple constructors and states using gen-class in clojure? 如何在clojure中使用gen-class定义多个构造函数和状态? I do not see a way to do this with single valued mappings for :init, :state and :constructors. 我没有看到使用单值映射执行此操作的方法:init,:state和:constructors。

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. 要在生成的类上拥有多个构造函数,您需要在gen-class的:constructors选项中指定的所有构造函数参数,并且:init函数应该是多个要匹配的。 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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM