I always thought that Predef.println
was merely a shortcut for System.out.println
, but apparently I am mistaken, since it doesn't seem to use System.out
at all. Why is that so? And how can I do the "redirecting" of System.out
below in Scala?
scala> val baos = new java.io.ByteArrayOutputStream baos: java.io.ByteArrayOutputStream = scala> val ps = new java.io.PrintStream(baos) ps: java.io.PrintStream = java.io.PrintStream@6c5ac4 scala> System.setOut(ps) scala> println("hello") hello scala> new String(baos.toByteArray) res2: java.lang.String = "" scala> System.out.println("hello") scala> new String(baos.toByteArray) res7: java.lang.String = "hello "
println() - It is used to print the statement. The system is a class, out is the object of PrintStream class, println() is the method of PrintStream class which displays the result and then throws the cursor to the next line.
Method # 1: Using the “println” Command The “println” command in the Scala programming language is used to print a line while introducing a new line at the end. In this way, if you want to print more than one line, each of them will be printed on a separate line.
The key difference between them is that printf() prints the formatted String into console much like System. out. println() but the format() method returns a formatted string, which you can store or use the way you want.
err which are commonly used to provide input to, and output from Java applications. Most commonly used is probably System. out for writing output to the console from console programs (command line applications).
Predef.println
is shortcut for Console.println
and you can use Console.setOut
or Console.withOut
for redirecting.
Also, Console.setOut
only affects the current thread while System.setOut affects the whole JVM. Additionally Scala 2.9 repl
evaluates each line in its own thread, so Console.setOut
is not usable there.
scala> val baos = new java.io.ByteArrayOutputStream baos: java.io.ByteArrayOutputStream = scala> Console.withOut(baos)(print("hello")) scala> println(baos) hello
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