簡體   English   中英

獲取clojure中對象類型的“默認值”嗎?

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

我想根據Clojure中對象的類型獲取對象的“默認值”。 例如,它可能像這樣工作:

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

在這兩種情況下,它都采用值的類型,並返回該值類型的“空白”實例。 我能想到的最好的是

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

但這不適用於數字:

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

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

看起來多方法可能是一個很好的選擇:

(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 ""

問題在於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.

Java說“ new Long()”是不合法的,這是newInstance()作用。 因此,您必須使用defmulti或等效方法手動進行defmulti

類型實際上沒有任何“默認值”之類的東西,除非您正在尋找不提供顯式值時Java默認初始化構造函數中內容的方式。 就是這樣:

  • 布爾=>假
  • 數字=> 0
  • object => null

如果您想要更復雜的內容(例如string =>“”),則必須通過將對象的類型以某種方式分派到您控制的代碼中來自己編寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM