New line character in Scala

Spread the love

Question Description

Is there a shorthand for a new line character in Scala? In Java (on Windows) I usually just use “\n”, but that doesn’t seem to work in Scala – specifically

val s = """abcd
efg"""
val s2 = s.replace("\n", "")
println(s2)

outputs

abcd
efg

in Eclipse,

efgd

(sic) from the command line, and

abcdefg

from the REPL (GREAT SUCCESS!)

String.format("%n") works, but is there anything shorter?

Practice As Follows

Your Eclipse making the newline marker the standard Windows \r\n, so you’ve got “abcd\r\nefg”. The regex is turning it into “abcd\refg” and Eclipse console is treaing the \r slightly differently from how the windows shell does. The REPL is just using \n as the new line marker so it works as expected.

Solution 1: change Eclipse to just use \n newlines.

Solution 2: don’t use triple quoted strings when you need to control newlines, use single quotes and explicit \n characters.

Solution 3: use a more sophisticated regex to replace \r\n, \n, or \r

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.