Scala Strings
Scala Strings
Section titled “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.
Creating Strings:
Section titled “Creating Strings:”Strings are typically created using string literals enclosed in double quotes.
val greeting: String = "Hello, world!"val language = "Scala"
// Multi-line stringsval multiLine = """This is amulti-linestring."""
@main def StringCreationDemo(): Unit = { println(greeting) println(language) println(multiLine)}Immutability:
Section titled “Immutability:”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().
String Interpolation:
Section titled “String Interpolation:”Scala offers powerful string interpolation for embedding variable values or expressions directly into string literals. This is often more readable than traditional concatenation.
s Interpolator:
Section titled “s Interpolator:”Prepends s to the string literal. Variables or expressions prefixed with $ are evaluated and inserted.
val name = "Alice"val age = 30val 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.f Interpolator:
Section titled “f Interpolator:”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 // metersval weight = 75.5 // kgval formatted = f"Height: $height%.2f meters, Weight: $weight%.1f kg"
println(formatted) // Output: Height: 1.83 meters, Weight: 75.5 kgraw Interpolator:
Section titled “raw Interpolator:”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\Documentsprintln(escaped) // Output: This has a newline // character.println(rawEscaped) // Output: This has a literal \n sequence.Common String Operations:
Section titled “Common String Operations:”Scala Strings inherit Java’s methods, and Scala’s RichString implicit conversion adds more.
| Method/Operator | Description |
|---|---|
length | Returns 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, toLowerCase | Changes 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. |
trim | Removes leading/trailing whitespace. |
isEmpty, nonEmpty | Checks if the string is empty. |
toIntOption, toDoubleOption, etc. | (From RichString) Safely convert to numeric types, returning Option. |
Example Usage:
Section titled “Example Usage:”val data = " Scala Programming "println(s"Length: ${data.length}") // Output: 21println(s"Char at 3: ${data.charAt(3)}") // Output: Cprintln(s"Trimmed: '${data.trim}'") // Output: 'Scala Programming'println(s"Uppercase: ${data.trim.toUpperCase}") // Output: SCALA PROGRAMMINGprintln(s"Contains 'Prog': ${data.contains("Prog")}") // Output: trueval parts = data.trim.split(" ")println(s"Split: ${parts.mkString(", ")}") // Output: Scala, Programmingval numStr = "123"println(s"To Int Option: ${numStr.toIntOption}") // Output: Some(123)val badNumStr = "abc"println(s"To Int Option: ${badNumStr.toIntOption}") // Output: NoneRefer to the java.lang.String and scala.collection.immutable.StringOps (via RichString) documentation for a full list of available methods.