Scala mkString
Join two stops with a visible route delimiter.
A simple example
mkString
- Start with a and b, separator -
- Do this Join using the separator
- Result a-b
object Lesson {
def main(args: Array[String]): Unit = {
val value = "a"
val other = "b"
println(List(value, other).mkString("-"))
}
}
a-b
Syntax
List(value, other).mkString(" → ")
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonPrint a campus shuttle route
A display receives an ordered list of items as separate values. Join them into one readable line with separators between neighboring values and no extra separator after the last one.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "Library"
val other = "Lab"
println(List(value, other).mkString(" → "))
}
}
Library → Lab
The arrow preserves the order of the two stops.
Show a parcel handoff
A transit or dispatch system receives journey information as a sequence of stops or handoffs. Preserve their order when interpreting or displaying the route so the next destination is clear.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "Depot"
val other = "Gate"
println(List(value, other).mkString(" → "))
}
}
Depot → Gate
The same delimiter separates the names.
Build a parcel shelf identifier
The shelf prefix already includes the hyphen. Combine the two fragments in order without adding another separator. What label goes to the printer?
What to watch for
Joining inserts a delimiter between elements. Include blank elements only if they represent a real stop.