7 minutes read

One of the basic programming tasks is interacting with users through messages, asking for the input, and providing an answer in the output. These messages are text sequences commonly known as Strings. In the most basic greeting program, a message like "Hello, Scala!" is actually a string! Since strings are really common and important in programming, let's learn more about this type in Scala.

Inside String

In Scala, String type is an immutable collection of characters. Let dive deeper into each of the points in the previous sentence. Since we know about collections and immutability, we can picture a string as an ordered collection of Char with a defined length. In this collection, just like in List, it is not possible to change one Char in the existing string: you have to generate a copy with the substitution.

This type is alias for java.lang.String, Java base type. Scala extends the basic functionality with a bunch of convenient methods, most revealing the collection side of strings. We will come back to these methods soon; let's start with defining Strings.

Defining Strings

You can define a String using the quotes " ":

scala> "This is a text"
res1: String = This is a text
scala> val s = ""
s: String = 

Multi-line strings can be defined with the help of triple quotes """ """:

scala> """This is text 
     | with several
     | lines"""
res2: String =
This is text
with several
lines

You can use special symbols to represent new lines, tabs, spaces, and so on:

scala> "Text with\nspecial\t symbols"
res3: String =
Text with
special  symbols

You can construct a new string from the existing ones using concatenation:

scala> s + s
res4: String = This is a text tooThis is a text too

A string is a collection of characters, so we can define it from the collection itself:

scala> val list = List('a', 'b', 'c')
list: List[Char] = List(a, b, c)
scala> list.mkString
res5: String = abc

Note that typically, we define Strings with Unicode encoding (UTF-8).

String transformations

Like we said before, Scala String originated from Java String, so you can run any method defined for the Java standard library. Here are some of them, just to recap: length, isEmpty, toUpperCase, startsWith, substring, replace, split.

Also, Scala provides some methods to transform String data:

  • filter, take, slice: there are plenty of methods defined for String as a sequence of characters. You can filter or divide a sequence forming a new String result:

scala> "Hello, Scala".take(5)
res6: String = Hello
scala> "Hello, Scala".slice(7, 12)
res7: String = Scala
  • sorted and sortBy return a result with sorted characters:

scala> "Hello, Scala".sorted
res8: String = " ,HSaacelllo"
  • stripPrefix, stripSuffix, and stripMargin cut the prefix, suffix, or the first specified character of every line:

scala> """D 
     |O
     |C""".stripMargin('|')
res9: String =
D
O
C
  • toBoolean, toByte, toShort, toInt, toLong, toFloat, toDouble convert String to another type:

scala> "123".toDouble
res10: Double = 123.0
scala> "123".toBoolean
java.lang.IllegalArgumentException: For input string: "123"
  • lines iterates over String lines:

scala> "First line\nSecond line".lines.next
res11: String = First line
  • Java charAt returns a character in the specified string position; it can be replaced by s(index):

scala> "Hello, Scala"(7)
res12: Char = S

Interpolation

Scala offers an interesting technique of inserting values in string statements:

scala> val i = 234
i: Int = 234

scala> s"i: $i"
res13: String = i: 234

scala> s"""i: $i"""
res14: String = i: 234

We prefix the string literal with s (short of standardInterpolator) and use the i value inside to substitute $i with the i value. The rules for substitution are simple: every part of a string statement starting with $ is substituted with a previously defined name, which could be a value, variable, or a function. You can use the extended syntax to deal with the more complicated statements:

scala> s"Output -i: ${-i},\nwith help of $$i" 
res14: String =
Output -i: -234,
with help of $i

Note that we can use the symbol $ and special symbols with the interpolated string.

Comparing Strings

Java has some tricky comparison for the String type: we can compare with == (compare references) or equals (compare values). In Scala, you can always compare by value with ==:

scala> val s1 = "A"
s1: String = A
scala> val s2 = "A"
s2: String = A
scala> s1 == s2
res17: Boolean = true
scala> s1 == "B"
res18: Boolean = false

Conclusion

Now you know how to define Scala Strings with different methods, transform String values using both Java and Scala methods, use interpolators to format text data, and compare Strings.

13 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo