I have written some utility programs in Java, and now I just want to translate it into Clojure. I am running into some snags with classes. Clojure touts that it has seamless interoperation with Java, but I have not been able to find good solution from Google. Please help. Thanks.
I want to use Java classes directly (I don't want to use clojure "format" function yet because I just want to see how the clojure-java-interop works out):
System.out.format("Enter number of points: ");
What I have done is:
(def x (. System out))
but then everything I tried to do to use format failed:
(. 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")
And what about translating System.exit(0) to clojure?
(. System exit 0)
does seem to work. But why doesn't similar translation work for "System.out.format"?
I seem like a monkey typing on the key board hoping to produce Hamlet!
Please help ! Thanks.
System.out.format takes in variable arguments. The way java dispatches var args functions is by shoving the rest of the arguments into an Object array. This could be achieved in clojure like so:
(. 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]))
actually lots of your attempts were really very close:
(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"]))
However, pay attention, this will print out to the repl console and not necessarily to what your ide shows.
To show it like clojure would, instead of using the java's System.out object, use clojure's *out*:
(. *out* format "abc %d" (into-array [12]))
;; "abc 12"
EDIT
It seems that your *out* is defined as a OutputStreamWriter which does not have the method format. Not sure why, but you could overcome this using binding, for example:
user=> (binding [*out* System/out]
(. *out* format "abc %d" (into-array[12])))
abc 12#object[java.io.PrintStream 0x4efb0c88 "java.io.PrintStream@4efb0c88"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With