为什么我的字符串格式在Clojure中失败?

qua*_*cle 8 clojure string-formatting

在Java中,我可以执行以下操作来格式化显示的浮点数:

String output = String.format("%2f" 5.0);
System.out.println(output);
Run Code Online (Sandbox Code Playgroud)

从理论上讲,我应该能够用这个Clojure做同样的事情:

(let [output (String/format "%2f" 5.0)]
    (println output))
Run Code Online (Sandbox Code Playgroud)

但是,当我在REPL中运行上面的Clojure片段时,我得到以下异常:

java.lang.Double cannot be cast to [Ljava.lang.Object;
[Thrown class java.lang.ClassCastException
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Kyl*_*ton 15

Java String.format需要一个Object[](或Object...),String.format在Clojure中使用,你需要将你的参数包装在一个数组中:

(String/format "%2f" (into-array [5.0]))
Run Code Online (Sandbox Code Playgroud)

Clojure为更容易使用的格式提供了一个包装器:

(format "%2f" 5.0)
Run Code Online (Sandbox Code Playgroud)

凯尔