String in Scala is simply java.lang.String. You can use String just like you do in Java. However, Scala does provide a few additional conveniences when working with String.
Scala can automatically convert a String to scala.runtime.RichString. This brings a few useful methods like capitalize, lines, and reverse to String.
It’s really simple in Scala to create a string that runs multiple lines—no more of those messy +=. Place the multiple lines of strings within three double quotes ("""…"""). That’s Scala’s support for the so-called here documents, or heredocs. To see it in action, let’s create a string that runs a few lines long:
FromJavaToScala/MultiLine.scala | |
| val str = """In his famous inaugural speech, John F. Kennedy said |
| "And so, my fellow Americans: ask not what your country can do |
| for you-ask what you can do for your country." He then proceeded |
| to speak to the citizens of the World...""" |
| println(str) |
The output is as follows:
| In his famous inaugural speech, John F. Kennedy said |
| "And so, my fellow Americans: ask not what your country can do |
| for you-ask what you can do for your country." He then proceeded |
| to speak to the citizens of the World... |
You can embed double quotes within the multiline strings as we saw in the previous example. Scala took the content within triple double quotes as is; this is called a raw string in Scala. In fact, Scala took the string too literally; the indentations in the code were carried into the string. We can trim the leading spaces using the method stripMargin of RichString, like this:
FromJavaToScala/MultiLine2.scala | |
| val str = """In his famous inaugural speech, John F. Kennedy said |
| |"And so, my fellow Americans: ask not what your country can do |
| |for you-ask what you can do for your country." He then proceeded |
| |to speak to the citizens of the World...""".stripMargin |
| println(str) |
stripMargin removes all blanks or control characters before the leading pipe (|). If the pipe symbol appears anywhere else other than the leading position on any line, it’s retained. If for some reason that symbol is sacred in an application, we can use a variation of the stripMargin method that accepts another preferred margin character. Here’s the output for the previous code:
| In his famous inaugural speech, John F. Kennedy said |
| "And so, my fellow Americans: ask not what your country can do |
| for you-ask what you can do for your country." He then proceeded |
| to speak to the citizens of the World... |
Raw strings are also useful when creating regular expressions. For example, it’s easier to type and to read """d2:d2""" than "\d2:\d2".
Heredocs help to create multiline strings, but we also often concatenate strings when creating messages for use, such as with println. You can remove that clutter using string interpolation.
3.142.114.245