Skip to content

Scala Strings

In Scala, strings are sequences of characters represented by the String type, which is directly backed by Java’s java.lang.String. This means Scala strings are immutable and you have access to all standard Java String methods.

Strings are typically created using string literals enclosed in double quotes.

val greeting: String = "Hello, world!"
val language = "Scala"
// Multi-line strings
val multiLine = """This is a
multi-line
string."""
@main def StringCreationDemo(): Unit = {
println(greeting)
println(language)
println(multiLine)
}

Like Java Strings, Scala Strings are immutable. Once created, a String object cannot be changed. Operations that appear to modify a string (like concatenation) actually create and return a new String object.

val s1 = "Hello"
val s2 = s1 + ", Scala!" // Creates a new String "Hello, Scala!"
println(s1) // Output: Hello (s1 remains unchanged)
println(s2) // Output: Hello, Scala!

For scenarios requiring many modifications, use scala.collection.mutable.StringBuilder for better performance, then convert back to a String using .toString().

Scala offers powerful string interpolation for embedding variable values or expressions directly into string literals. This is often more readable than traditional concatenation.

Prepends s to the string literal. Variables or expressions prefixed with $ are evaluated and inserted.

val name = "Alice"
val age = 30
val message = s"My name is $name and I am $age years old."
val complexMessage = s"Next year, I will be ${age + 1}."
println(message) // Output: My name is Alice and I am 30 years old.
println(complexMessage) // Output: Next year, I will be 31.

Prepends f to the string literal. Allows formatting embedded values using printf-style format specifiers after the variable/expression, followed by %.

val height = 1.825 // meters
val weight = 75.5 // kg
val formatted = f"Height: $height%.2f meters, Weight: $weight%.1f kg"
println(formatted) // Output: Height: 1.83 meters, Weight: 75.5 kg

Prepends raw to the string literal. Similar to s, but does not process escape sequences (like \n, \t).

val path = raw"C:\Users\Default\Documents"
val escaped = s"This has a newline \n character."
val rawEscaped = raw"This has a literal \n sequence."
println(path) // Output: C:\Users\Default\Documents
println(escaped) // Output: This has a newline
// character.
println(rawEscaped) // Output: This has a literal \n sequence.

Scala Strings inherit Java’s methods, and Scala’s RichString implicit conversion adds more.

Method/OperatorDescription
lengthReturns the number of characters.
charAt(index)Returns the character at the specified index.
concat(str) or +Concatenates strings.
substring(begin, end)Extracts a portion of the string.
toUpperCase, toLowerCaseChanges case.
startsWith(prefix), endsWith(suffix)Checks prefix/suffix.
contains(substring)Checks if a substring exists.
indexOf(char/str), lastIndexOf(char/str)Finds index of first/last occurrence.
replace(oldChar, newChar), replaceAll(regex, replacement)Replaces characters or patterns.
split(separator)Splits the string into an array based on a separator.
trimRemoves leading/trailing whitespace.
isEmpty, nonEmptyChecks if the string is empty.
toIntOption, toDoubleOption, etc.(From RichString) Safely convert to numeric types, returning Option.
val data = " Scala Programming "
println(s"Length: ${data.length}") // Output: 21
println(s"Char at 3: ${data.charAt(3)}") // Output: C
println(s"Trimmed: '${data.trim}'") // Output: 'Scala Programming'
println(s"Uppercase: ${data.trim.toUpperCase}") // Output: SCALA PROGRAMMING
println(s"Contains 'Prog': ${data.contains("Prog")}") // Output: true
val parts = data.trim.split(" ")
println(s"Split: ${parts.mkString(", ")}") // Output: Scala, Programming
val numStr = "123"
println(s"To Int Option: ${numStr.toIntOption}") // Output: Some(123)
val badNumStr = "abc"
println(s"To Int Option: ${badNumStr.toIntOption}") // Output: None

Refer to the java.lang.String and scala.collection.immutable.StringOps (via RichString) documentation for a full list of available methods.