Strings

This is the first of three lessons on the Scala String data type.

Strings are:

  • Enclosed in double-quotes
  • Enclosed in triple-quotes (multiline strings)
  • Immutable
  • A String can also be treated as a Seq[Char]
val x = "Alvin"

Multiline string:

val x = """
Alvin
123 Main Street
Talkeetna, AK 99676
""""

Common String methods

val s = "big belly burger"
s.length
s.capitalize
s.toUpperCase
s.take(3)
s.drop(4)
s.startsWith("b")
s.endsWith("er")
s.distinct
s.intersect("big")

Higher-order functions (HOFs)

A primary use of an HOF is that it’s a function that takes other functions as input parameters:

s.map(c => c.toUpper)
s.filter(c => !c.isSpaceChar)
s.dropWhile(c => c != 'e')

String is also a Seq[Char]

s(0)
for c <- s do println(c)

Many more methods!

See my blog post: