Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

println vs System.out.println in Scala

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 " 
like image 705
Kim Stebel Avatar asked Aug 28 '11 05:08

Kim Stebel


People also ask

What is the difference between out Println and system out Println?

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.

What is Println in Scala?

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.

What is the difference between system out Println and system out format?

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.

What is the use of system err?

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).


1 Answers

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 
like image 173
4e6 Avatar answered Sep 24 '22 01:09

4e6