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?
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.
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.
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.
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.
scala> import util.Properties
import util.Properties
scala> Properties.lineSeparator
res14: java.lang.String =
"
"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With