Our first program will demonstrate strings and runes in Scala. Here’s the full source code:
To run the program, save it as StringsAndRunes.scala and use scala command:
In Scala, strings are sequences of characters, and each character is a Unicode code point. Unlike in some other languages, Scala doesn’t have a separate concept of “runes”. Instead, characters in Scala are 16-bit Unicode characters.
The length method on a string returns the number of characters, not the number of bytes. This means that even for strings containing multi-byte Unicode characters (like Thai), length will return the number of visible characters.
Scala’s foreach method and for comprehensions provide convenient ways to iterate over the characters in a string. The zipWithIndex method is used to pair each character with its index in the string.
The toInt method on a character returns its Unicode code point, which we format as a hexadecimal value for display.
In the examineChar function, we demonstrate how to compare a character to a literal value. Scala uses single quotes for character literals.
This example shows how Scala handles Unicode strings and characters, providing a straightforward way to work with text in various languages and scripts.