1. Overview

In this tutorial, we’ll discuss converting an Array‘s content to a String in Kotlin. First, we’ll explore four distinct methods to achieve this. Then, we’ll compare them based on their conciseness, immutability, and simplicity.

We’ll start with the built-in method contentToString(), which internally uses Java’s static method Arrays.toStirng(). After that, we’ll learn how to aggregate the elements using the reduce() and fold(). Finally, we’ll implement the same functionality by concatenating the elements within a simple for-loop.

2. contentToString()

The method contentToString() is the straightforward way of converting an Array‘s content to String. This method returns a String containing all the elements from the array, joined by commas:

val stringArray: Array<String> = arrayOf("java", "kotlin", "scala")
assertEquals("[java, kotlin, scala]", stringArray.contentToString())

Moreover, if we call contentToString() on an array of elements that are not Strings, the toString() method will be called first:

val intArray: IntArray = intArrayOf(9, 8, 7, 6)
assertEquals("[9, 8, 7, 6]", intArray.contentToString())

This can be a convenient way of quickly converting the content to String, and it can be useful for logging and debugging. However, we won’t have any control over the structure of the resulting String. For instance, if we want to remove the enclosing square brackets or use a different delimiter, we’ll need to call additional methods such as replace().

3. reduce()

The reduce() method offers far more flexibility, allowing us to fully control the structure of the resulting String. For example, we can employ it to remove the enclosing square brackets and join the elements with semicolons instead of commas:

val stringArray: Array<String> = arrayOf("java", "kotlin", "scala")

val result = stringArray.reduce { result, nr -> "$result; $nr" }

assertEquals("java; kotlin; scala", result)

The reduce() method aggregates multiple elements of a type into a resulting element of the same type. So, if we don’t start from an Array of Strings, we’ll need to manually map() the elements to their String equivalent first:

val intArray: IntArray = intArrayOf(9, 8, 7, 6)

val result = intArray
  .map { it.toString() }
  .reduce { result, nr -> "$result; $nr" }

assertEquals("9; 8; 7; 6", result)

As we can notice, this approach gives us full control over the final structure of the result. Firstly, we can customize the map() method to define the way each element should be displayed as a String. Then, we can specify how these elements should be concatenated together via the reduce(). 

4. fold()

We can also implement this using the fold() method, which functions similarly to reduce() but offers the added flexibility of modifying the aggregated type. This enables us to bypass the map() step altogether and provide a default value, such as an empty string, in our scenario.

However, the empty String that we are passing to the fold() method will be used as the initial value for the intermediary result variable. Therefore, we’ll need to add an if statement to avoid adding the extra semicolon at the beginning of the String:

val intArray: IntArray = intArrayOf(9, 8, 7, 6)

val result = intArray.fold("") { result, nr ->
    if (result.isEmpty()) "$nr" else "$result; $nr"
}

assertEquals("9; 8; 7; 6", result)

5. for Loop

Lastly, we can use a simple for loop and a String variable where we continuously append the elements. Let’s start by initializing this String with the first element of the Array and then update it as we iterate the collection:

val intArray: IntArray = intArrayOf(9, 8, 7, 6)

var result = intArray[0].toString()
for (i in 1 ..< intArray.size) {
    result += "; ${intArray[i]}"
}

assertEquals("9; 8; 7; 6", result)

6. Conclusion

In this tutorial, we explored four different ways of converting an Array‘s content to a String. We began by looking into the built-in method contentToString(). After that, we explored the methods inherited from functional programming, such as reduce() and fold(). Finally, we discussed the less-declarative solution with a simple for loop and a non-final String variable.

As always, the source code of the examples is available over on GitHub.

Comments are closed on this article!