Start learning free

SCALA · STRINGS

Intro To Strings in Scala, explained

What a string is

A string is a sequence of characters: letters, digits, spaces and punctuation. Scala has no string type of its own. The type String is Java's java.lang.String, available without an import, so everything Java strings can do works in Scala too. On top of that, Scala adds many collection-style methods such as take, drop, reverse and indices.

You write a string literal between double quotes:

val greeting = "Hello"
val empty = ""
val sentence = "Scala has strings, too."

A single character is a different type, Char, and uses single quotes: 'H'. A string of length 1, "H", is still a String, and the two are not interchangeable.

Strings are ordered and indexed

Each character has a position, called an index, and counting starts at 0. For "Hello", 'H' is at index 0 and 'o' is at index 4. The last valid index is always the length minus one.

val s = "Hello"
println(s.length)        // 5
println(s(0))            // H
println(s(s.length - 1)) // o

Scala reads a character with parentheses, s(0), not square brackets. Reading an index that doesn't exist, such as s(10), throws a StringIndexOutOfBoundsException. Off-by-one mistakes with length are the most common way to hit it.

Strings cannot be changed

A String is immutable: once it exists, its characters never change. Methods that look like they modify a string actually return a new one and leave the original alone.

val word = "scala"
val loud = word.toUpperCase
println(word) // scala
println(loud) // SCALA

Assignment is different from changing. A var can be pointed at a new string, but that doesn't alter the old one. With a val, even that is not allowed, and the compiler rejects a second assignment.

Building and cutting strings

The + operator joins strings into a new one, and += on a var joins and stores the result back. The method substring(start, end) returns the part from start up to but not including end. With one argument, it runs to the end of the string.

var lang = "Java"
lang += "script"                // Javascript
println(lang.substring(4))      // script
println(lang.substring(0, 4))   // Java

Joining a string with a number also gives a string, and the order of evaluation matters: "Hi" + 1 + 2 is "Hi12", while 1 + 2 + "Hi" is "3Hi", because the two numbers are added first.

String interpolation is often neater than a chain of +. A literal with an s in front accepts $name and ${expression}:

val name = "John"
println(s"Hello $name, you have ${name.length} letters")

The output is Hello John, you have 4 letters.

Looping over characters

A string works like a sequence of Char values, so a for loop can walk through it directly or through its indices:

for (c <- "Andy") print(c + "|")  // A|n|d|y|
println()
for (i <- "Andy".indices) println(i)  // 0, 1, 2, 3

Visiting every character takes O(n) time for a string of length n.

Comparing strings

In Scala, == compares the contents of two strings, so "abc" == "ab" + "c" is true. You don't need a method like Java's equals for ordinary comparisons.

Why strings matter in interviews

Many interview problems are string problems: checking whether a word reads the same backwards, reversing the words in a sentence, counting characters or comparing two texts. Because strings are immutable, building a result one += at a time copies the text on every step. For a few characters that is fine; for a long loop, the better tools are a StringBuilder or converting the string to an Array[Char], changing the array in place and turning it back into a string. The next lessons in this chapter practise exactly these operations: indexing, slicing, concatenation, searching and converting.

Key takeaways

  • String is Java's string type, with extra Scala methods; Char is a separate type written with single quotes.
  • Indices start at 0, you read a character with s(i), and the last index is s.length - 1.
  • Strings are immutable: operations return new strings.
  • +, += and interpolation build strings; substring cuts them, with the end index excluded.
  • == compares contents.
Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
Start learning free