简体   繁体   English

获取clojure中对象类型的“默认值”吗?

[英]Get the “default value” of an object's type in clojure?

I want to get the "default value" of an object based on its type in clojure. 我想根据Clojure中对象的类型获取对象的“默认值”。 For example, it might work like this: 例如,它可能像这样工作:

(default-value 15) ;; => 0
(default-value "hi") ;; => ""

In both cases, it takes the type of the value, and returns a "blank" instance of that value's type. 在这两种情况下,它都采用值的类型,并返回该值类型的“空白”实例。 The best I can come up with is 我能想到的最好的是

(defn default-value [x] (.newInstance (.getClass x)))

But this doesn't work on numbers: 但这不适用于数字:

repl=> (.newInstance (.getClass 1))

NoSuchMethodException java.lang.Long.<init>()  java.lang.Class.getConstructor0 (Class.java:3082)

Looks like multimethods could be a good fit: 看起来多方法可能是一个很好的选择:

(defmulti   getNominalInstance (fn [obj] (.getClass obj)))
(defmethod  getNominalInstance java.lang.Long   [obj] (Long. 0))
(defmethod  getNominalInstance java.lang.String [obj] "")

(prn :long    (getNominalInstance 5))
(prn :string  (getNominalInstance "hello"))

;=> :long 0
;=> :string ""

The problem is that Long only has 2 constructors, which take either a primitive long or a string, respectively. 问题在于Long仅具有2个构造函数,它们分别采用原始的long或字符串。

Long(long value) - Constructs a newly allocated Long object 
that represents the specified long argument.

Long(String s) - Constructs a newly allocated Long object 
that represents the long value indicated by the String parameter.

It isn't legal Java to say "new Long()", which is what newInstance() does. Java说“ new Long()”是不合法的,这是newInstance()作用。 So, you have to do it manually with defmulti or equivalent. 因此,您必须使用defmulti或等效方法手动进行defmulti

There's not really any such thing as a "default value" for a type, unless you are looking for the way that Java default-initializes stuff in constructors when you don't provide an explicit value. 类型实际上没有任何“默认值”之类的东西,除非您正在寻找不提供显式值时Java默认初始化构造函数中内容的方式。 That's just: 就是这样:

  • boolean=>false 布尔=>假
  • number=>0 数字=> 0
  • object=>null object => null

If you want something more sophisticated (eg, string=>"") you will have to write it yourself, by dispatching somehow on the type of the object into code you control. 如果您想要更复杂的内容(例如string =>“”),则必须通过将对象的类型以某种方式分派到您控制的代码中来自己编写。

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

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