Kotlin: Convert a list to a String (joinToString syntax/example)

Here’s a little Kotlin joinToString example. First, a sample list to work with:

val nums = listOf(1,2,3,4,5)

Then here’s the joinToString example:

nums.joinToString(
    separator = ", ",
    prefix = "[",
    postfix = "]",
    limit = 3,
    truncated = "there’s more ..."
)

When you put all of that code in the Kotlin REPL you’ll see this result:

[1, 2, 3, there’s more ...]

A few notes about that example:

  • You can see the separator, prefix, and postfix in the output
  • Only the numbers 1, 2, and 3, are printed because the limit is set to 3
  • The “there’s more...truncated text is printed after the third value

In summary, I hope this Kotlin joinToString example is helpful.