String
A String is a piece of text, like a word or sentence on a ribbon. Once made it cannot be edited in place, so changes produce a new string.
In this page:
Syntax
val text: String = "some text"
text.length
text.toUpperCase
String
A String is an immutable sequence of characters, written with double quotes. Strings support concatenation with +, a rich set of built-in methods, and interpolation with s"..." (covered in its own tutorial).
Because strings are immutable, every "modification" actually creates a new string.
Note:
Prefer string interpolation (
s"Hello $name") over + concatenation for readability.Example: String
object Main extends App {
val first = "Ada"
val last = "Lovelace"
val full = first + " " + last
println(full)
println(full.length)
println(full.toUpperCase)
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to change a string in place like
s(0) = X, when strings are immutable and you must create a new one. - Comparing strings with
eqand expecting content comparison, when==compares the content. - Forgetting that
full.lengthtakes no parentheses in the code, and writingfull.length()where the style differs; both work but Scala convention omits them.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: