Library contents

Kotlin joinToString

Join two stops with a visible route delimiter.

A simple example

joinToString

  1. Start with a and b, separator -
  2. Do this Join using the separator
  3. Result a-b
The separator goes between the two pieces exactly once.
Lesson.kt
fun main() {
    val value = "a"
    val other = "b"
    println(listOf(value, other).joinToString("-"))
}
Output
a-b

Syntax

Kotlin syntax
listOf(value, other).joinToString(" → ")
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Print 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.

From the programval value = "Library"
ResultLibrary → Lab
Lesson.kt
fun main() {
    val value = "Library"
    val other = "Lab"
    println(listOf(value, other).joinToString(" → "))
}
Output
Library → Lab

The arrow preserves the order of the two stops.

Advertisements

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.

From the programval value = "Depot"
ResultDepot → Gate
Lesson.kt
fun main() {
    val value = "Depot"
    val other = "Gate"
    println(listOf(value, other).joinToString(" → "))
}
Output
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?

Given'North-' · '12'
Worked resultNorth-12

What to watch for

Joining inserts a delimiter between elements. Include blank elements only if they represent a real stop.

Documentation for joinToString