1. Overview

In this tutorial, we’re going to look into Strings in Scala.

2. Defining a String

We can define a String as a single line String wrapped in double-quotes:

val singleLineString = "Hello, I am a single line string"

Additionally, it can be defined as a multi-line String wrapped in three double quotes:

val multiLineString = """Hello, I am  
  |a multiline
  |String""".stripMargin

With the pipe character and stripMargin method, we just left-justified our text.

3. String Equality

Comparing two Strings in Scala is handled using the == operator. First, the method checks for potential null values, and then calls the equals method on String to compare:

assert("Hello, I am a single line string" == singleLineString)

4. String Concatenation

We can concatenate Strings using the concat method or the + operator:

val askTheTimeString = "...What time is it?"

val concatStrWithConcat = singleLineString.concat(askTheTimeString)
assert(concatStrWithConcat == "Hello, I am a single line string...What time is it?")

val concatStr = singleLineString + askTheTimeString
assert( concatStr == "Hello, I am a single line string...What time is it?")

5. String Matching with Regular Expressions

Scala supports regular expressions through the Regex class, available in the scala.util.matching package. Using the r method on a String, we can convert it to a Regex instance, where we can perform String matching:

val testString = "this is a string with numbers 123456"
val regEx: Regex = "^(?=.*[a-zA-Z])(?=.*[0-9])".r

val result = regEx
  .findFirstMatchIn(testString)
  .isDefined
assertTrue(result == true)

In the above example, we’re checking if a String contains both letters and numbers.

It’s also possible to match groups of regular expressions using parenthesis, so let’s see how it works and first define a multi-line String:

val testString = """property1: value1
    |property2: value2
    |property"""

Suppose we want to match all the key-value properties contained in the multi-line String. To achieve this, we can define a group of regular expressions and match them:

val regExGroup = "([0-9a-zA-Z- ]+): ([0-9a-zA-Z-#()/. ]+)".r
val matchResults = regExGroup.findAllMatchIn(testString)

As a result, the match will contain only the key-value properties that match the regular expressions:

val matchedStrings = matchResult
  .map(regExMatch => 
    s"key: ${(regExMatch.group(1)} value: ${(regExMatch.group(2)}"
  ).mkString(System.lineSeparator)

val expected = """key: property1 value: value1
                 |key: property2 value: value2"""
  .stripMargin

assert(matchedStrings.equals(expected))

6. String Interpolation

String interpolation in Scala can be obtained with s, f, and raw methods.

Using s interpolation we can use our variables directly in the literal String, for instance:

val age = 30
val agePresentation = s"I am $age"
assert("I am 30" == agePresentation)

With f interpolation we have type-safe interpolation:

val >val name = "Michele"
val interpStr = f"My name is $name%s. I am $age%d years old and $height%1.2f meters tall"
assert(interpStr == "My name is Michele. I am 30 years old and 1,70 meters tall")

Finally, raw interpolation is similar to s interpolation except that it doesn’t escape literals:

val result = raw"My name is $name%s. \n $agePresentation and $height%1.2f meters tall"
assert(result == "My name is Michele%s. \\n I am 30 and 1.7%1.2f meters tall")

7. Conclusion

In this article, we looked at some of the main operations that we can do with Strings in Scala. As usual, the full source code can be found over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.