println vs System.out.println in Scala
Asked Answered
O

1

47

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
"
Overrule answered 28/8, 2011 at 5:58 Comment(1)
See issues.scala-lang.org/browse/SI-4793.Hydrophobic
A
43

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
Attainment answered 28/8, 2011 at 7:5 Comment(2)
'without' sounds somehow wrong, even the big O doesn't heal it. :)Drew
@userunknown Agreed. To make matters even worse, there's even a Console.withIn.Mercaptide

© 2022 - 2024 — McMap. All rights reserved.