1. Overview

One of the most common operations in software development is to print the content of a List in some specific format.

In this tutorial, we’ll explore different techniques to print a List‘s elements separated by a comma in Kotlin.

2. Using a for Loop

The first technique uses the for control to iterate through the List and manually print the elements separated by commas:

val myList = listOf("apple", "banana", "cherry", "date")
var result = ""
for (item in myList) {
    result += if (result.isEmpty()) item else ", $item"
}
assertEquals("apple, banana, cherry, date", result)

3. Using joinToString Function

Kotlin provides a built-in function joinToString that makes it straightforward to concatenate the elements of a List with a separator:

val myList = listOf("apple", "banana", "cherry", "date")
val result = myList.joinToString(", ")
assertEquals("apple, banana, cherry, date", result)

4. Using the reduce Function

In Kotlin, the reduce method is a higher-order function that is often used for combining the elements of a collection into a single result. We can take advantage of the reduce function to concatenate the elements in the List:

val myList = listOf("apple", "banana", "cherry", "date")
val result = myList.reduce { acc, s -> "$acc, $s" }
assertEquals("apple, banana, cherry, date", result)

5. Conclusion

Printing the contents of a List separated by commas in Kotlin can be achieved using various methods. The joinToString function provides a very concise and readable solution. However, using a for loop or the reduce function can be helpful in situations where we need more manual control over the process.

As always, the complete code for this article is available over on GitHub.