Multiline Strings (Scala 3 Video)
This is the second of three lessons on the Scala String
data type.
Use triple-quotes to create multiline strings:
val address = """
Alvin Alexander
123 Main Street
Talkeetna, AK 99676
"""
Formatting multiline strings
- With
stripMargin
and|
- Using a different character, like
#
Without stripMargin
:
val a = 1
val b = "two"
val c = s"""
$a
$b
"""
With stripMargin
:
val c = s"""
|$a
|$b
""".stripMargin.trim
// with stripMargin('c')
val c = s"""
#$a
#$b
""".stripMargin('#').trim
Multiline formatted string that uses a class and class members:
case class Address(
street1: String,
street2: String,
city: String,
state: String,
zip: String
)
val a = Address(
"P.O. Box 123",
"",
"Talkeetna",
"AK",
"99676"
)
val formattedAddress = s"""
|${a.street1}
|${a.street2}
|${a.city}, ${a.state} ${a.zip}
""".stripMargin.trim
Update: All of my new videos are now on
LearnScala.dev