将System.out.format转换为Clojure

时间:2016-08-18 07:24:41

标签: java class clojure format interop

我用Java编写了一些实用程序,现在我只是想 将其翻译成 Clojure 。我遇到了一些障碍 类。 Clojure宣称它与Java无缝互操作, 但我无法从谷歌找到好的解决方案。请 救命。感谢。

我想直接使用Java类(我不想使用clojure “格式”功能还没有,因为我只是想看看如何 clojure-java-interop 可以解决):

System.out.format("Enter number of points: ");

我所做的是:

(def x (. System out))

但是我尝试使用格式的所有内容都失败了:

(. x format "foo")
(. x (format "foo"))
(.format x)
(.format "foo")
(. x format)
(. x #(format))
(. x #(format %) "s")
(.format x "foo")
((.format x) "foo")
(x/format "foo")
(x. format "%s" "foo")
(. x format "%s" "s")
(. x format "%s" ["s"])
(def y (System.out.))
(def y (System.out.format.))
(format x "s")

那么将System.exit(0)翻译成clojure呢?

(. System exit 0) 

似乎确实奏效了。但为什么类似的翻译不适用于“System.out.format”?

我好像在键盘上打字,希望生产哈姆雷特!

请帮忙!感谢。

2 个答案:

答案 0 :(得分:3)

System.out.format接受变量参数。 java调度var args函数的方法是将其余参数推送到Object数组中。这可以通过如下方式实现:

(. System/out format "abc" (into-array []))
(. System/out format "abc %d" (into-array [12]))

;; or use the more intuitive
(.format System/out "abc %d" (into-array[12]))

实际上很多尝试都非常接近:

(def x (. System out))
(. x format "foo" (into-array[]))
(. x (format "foo" (into-array[])))
(.format x "foo" (into-array[]))
(. x format "%s" (into-array["foo"]))

然而,请注意,这将打印到repl控制台,而不一定是你的ide显示。

要像clojure一样显示它,而不是使用java的System.out对象,请使用clojure' s *out*

(. *out* format "abc %d" (into-array [12])) 
;; "abc 12"

修改

您的*out*似乎定义为OutputStreamWriter,但没有方法format。不确定原因,但你可以使用绑定来克服这个问题,例如:

user=> (binding [*out* System/out]
         (. *out* format "abc %d" (into-array[12])))
abc 12#object[java.io.PrintStream 0x4efb0c88 "java.io.PrintStream@4efb0c88"]

答案 1 :(得分:1)

Clojure已经有printf函数与PrintStream.format做同样的事情,除了它专门打印到*out*

(printf "Enter number of points: ")
;; Enter number of points: 

(printf "abc %d" 12)
;; abc 12