Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the line separator of current os easily in Scala?

Tags:

newline

scala

I remember in Java, we do it like this:

System.getProperty("line.separator")

How to do the same in scala? Is there a better(easier) way?

like image 943
Freewind Avatar asked Feb 10 '12 15:02

Freewind


People also ask

What is System line separator?

The lineSeparator() is a built-in method in Java which returns the system-dependent line separator string. It always returns the same value – the initial value of the system property line.

How do I add a line in Scala?

To write the second line into a new line, write a new line character to the file after the first line. New line character is indicated by "\n". so, you will write "Hello Scala", then "\n" followed by "Bye Scala" to the file.

Is the line separator the same on all platforms What is the line separator on Windows?

The line separator varies from computer to computer, from Operating System to Operating System. You will get different line separators on Windows and Unix. If you run this: System. getProperty("line.

How do you make a new line character in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


2 Answers

scala> import util.Properties
import util.Properties

scala> Properties.lineSeparator
res14: java.lang.String =
"
"
like image 197
missingfaktor Avatar answered Oct 12 '22 04:10

missingfaktor


Both scala.util.Properties.lineSeparator and System.lineSeparator will do the same job.

System.lineSeparator will directly call Java method which has to find property in systems props:

lineSeparator = props.getProperty("line.separator");

Here is the result:

scala> System.lineSeparator
res0: String = 
"
"

It falls back to default Java props if none found.

Similarly, Properties.lineSeparator will call:

def lineSeparator = propOrElse("line.separator", "\n")

which eventually calls:

System.getProperty(name, alt)

Result is the same:

scala> scala.util.Properties.lineSeparator
res2: String = 
"
"

So they both get line separator from Java props. The only difference is how they get defaults. I don't know why it's implemented this way :). It's like they don't trust that Java will have correct default in this case.

like image 40
yǝsʞǝla Avatar answered Oct 12 '22 03:10

yǝsʞǝla