joinToString

Common
JVM
JS
Native
1.0
fun <T> Sequence<T>.joinToString(
    separator: CharSequence = ", ",
    prefix: CharSequence = "",
    postfix: CharSequence = "",
    limit: Int = -1,
    truncated: CharSequence = "...",
    transform: ((T) -> CharSequence)? = null
): String

(source)

Creates a string from all the elements separated using separator and using the given prefix and postfix if supplied.

If the collection could be huge, you can specify a non-negative value of limit, in which case only the first limit elements will be appended, followed by the truncated string (which defaults to "...").

The operation is terminal.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val numbers = listOf(1, 2, 3, 4, 5, 6)
println(numbers.joinToString()) // 1, 2, 3, 4, 5, 6
println(numbers.joinToString(prefix = "[", postfix = "]")) // [1, 2, 3, 4, 5, 6]
println(numbers.joinToString(prefix = "<", postfix = ">", separator = "•")) // <1•2•3•4•5•6>

val chars = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q')
println(chars.joinToString(limit = 5, truncated = "...!") { it.uppercaseChar().toString() }) // A, B, C, D, E, ...!
//sampleEnd
}