In Clojure 1.11, I’m evaluating this term:
(apply println "foo\n" "bar\n" "baz\n")
I expect the following output:
foo
bar
baz
However, I’m getting this:
foo
bar
b a z
The first line is as I need it. The second line contains a leading space. The third line has a superfluous space before each letter.
Why is behaving apply/println like that, and how can I get the desired output?
>Solution :
Leading spaces come from the fact that println adds spaces when printing its arguments. E.g. try (println 1 2 3) – you’ll get 1 2 3 in the output.
The last line comes out as it does because you’re using apply. apply treats the last argument as a collection as passes its items as separate arguments to the target function. So in this case you most likely don’t need apply at all.
To achieve what you want, you should use something like (run! print ["foo\n" "bar\n" "baz\n"]). Or use println and don’t add \n yourself since println does that for you.