This article explores different ways to print contents of a List separated by a comma in Kotlin.

1. Using joinToString() function

The standard solution to concatenate all the list elements with a separator is with the joinToString() function.

Download Code

 
The joinToString() function is overloaded to accept the prefix and postfix as well.

Download Code

2. Using String.join() function

If you don’t mind using Java’s String class, you can use the String.join() function. It connects all strings in a List together with the specified separator.

Download Code

3. Using StringJoiner class

Another Java-based solution involves using the StringJoiner class to construct a sequence of elements separated by a separator.

Download Code

 
To create a string beginning with the given prefix and ending with the given postfix, do like:

Download Code

4. Using String builder

The String builder can be used to efficiently perform multiple string manipulation operations. The following code example demonstrates the usage of String builder, to collect contents of a List separated by a comma.

Download Code

That’s all about printing contents of a List separated by a comma in Kotlin.