Scala中的println与System.out.println [英] println vs System.out.println in Scala
问题描述
我一直认为 Predef.println
仅仅是 System.out.println
的快捷方式,但显然我弄错了,因为它似乎根本不使用 System.out
。为什么?以及如何在Scala中重定向下面的 System.out
?
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
"
推荐答案
Predef.println
是 Console.println $的快捷方式c $ c>,则可以使用
Console.setOut
或 Console.withOut
进行重定向。
Predef.println
is shortcut for Console.println
and you can use Console.setOut
or Console.withOut
for redirecting.
此外, Console.setOut
仅影响当前线程,而System.setOut
影响整个JVM 。另外,Scala 2.9 repl
会在其自己的线程中评估每一行,因此 Console.setOut
在那里不可用。
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
这篇关于Scala中的println与System.out.println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!