Scala 中的 println 与 System.out.println
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7219316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
println vs System.out.println in Scala
提问by Kim Stebel
I always thought that Predef.printlnwas merely a shortcut for System.out.println, but apparently I am mistaken, since it doesn't seem to use System.outat all. Why is that so? And how can I do the "redirecting" of System.outbelow in Scala?
我一直认为这Predef.println只是 的捷径System.out.println,但显然我错了,因为它似乎根本没有使用System.out。为什么呢?我怎样才能System.out在 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
"
采纳答案by 4e6
Predef.printlnis shortcut for Console.printlnand you can use Console.setOutor Console.withOutfor redirecting.
Predef.println是Console.println您可以使用Console.setOut或Console.withOut用于重定向的快捷方式。
Also, Console.setOutonly affects the current thread while System.setOut
affects the whole JVM. Additionally Scala 2.9 replevaluates each line in its own thread, so Console.setOutis not usable there.
此外,Console.setOut仅影响当前线程,而 System.setOut 影响整个 JVM。此外,Scala 2.9repl在自己的线程中评估每一行,因此Console.setOut在那里不可用。
scala> val baos = new java.io.ByteArrayOutputStream
baos: java.io.ByteArrayOutputStream =
scala> Console.withOut(baos)(print("hello"))
scala> println(baos)
hello

