Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

mkString

The mkString method is available for all collections in Scala, including lists, sets, arrays, etc. It can be used with or without delimiters.

Basic mkString without Delimiters

Concatenates all elements of the collection into a single string.

val numbers = List(1, 2, 3, 4, 5)
val result = numbers.mkString
println(result) // "12345"

mkString with a Separator

Concatenates all elements of the collection into a single string with a specified separator between elements.

val numbers = List(1, 2, 3, 4, 5)
val result = numbers.mkString(", ")
println(result) // "1, 2, 3, 4, 5"

mkString with Prefix, Separator, and Suffix

Concatenates all elements of the collection into a single string with a specified prefix, separator, and suffix.

val numbers = List(1, 2, 3, 4, 5)
val result = numbers.mkString("[", ", ", "]")
println(result) // "[1, 2, 3, 4, 5]"

Use Cases

Joining File Paths

val parts = List("home", "user", "documents", "file.txt")
val filePath = parts.mkString("/")
println(filePath) // "home/user/documents/file.txt"

Generating CSV Lines

val headers = List("Name", "Age", "City")
val row1 = List("Alice", "30", "New York")
val row2 = List("Bob", "25", "Los Angeles")

val csvHeaders = headers.mkString(", ")
val csvRow1 = row1.mkString(", ")
val csvRow2 = row2.mkString(", ")

println(csvHeaders) // "Name, Age, City"
println(csvRow1)    // "Alice, 30, New York"
println(csvRow2)    // "Bob, 25, Los Angeles"

Creating SQL Query IN Clause

val ids = List(1, 2, 3, 4, 5)
val sqlInClause = ids.mkString("(", ", ", ")")
println(sqlInClause) // "(1, 2, 3, 4, 5)"