Kotlin Array contentToString()

Kotlin Array contentToString()

In Kotlin, the Array contentToString() function is used to obtain a string representation of the content of an array. It returns a string containing the elements of the array enclosed in square brackets.

This function is helpful when you want to quickly inspect the content of an array in a human-readable format.

In this tutorial, we’ll explore the syntax of the Array contentToString() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the contentToString() function is:

fun <T> Array<out T>.contentToString(): String

The contentToString() function returns a string representation of the content of the array.

Examples for Array contentToString() function

1. Using contentToString() with an Array of Numbers

In this example, we’ll use contentToString() to obtain a string representation of an array of numbers numbersArray.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)

    // Using contentToString() to obtain a string representation
    val arrayString = numbersArray.contentToString()

    // Printing the string representation of array
    println(arrayString)
}

Output

[10, 20, 30, 40, 50]

2. Using contentToString() with an Array of Strings

In this example, we’ll use contentToString() to obtain a string representation of an array of strings fruitsArray.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("apple", "banana", "orange", "kiwi")

    // Using contentToString() to obtain a string representation
    val arrayString = fruitsArray.contentToString()

    // Print the resulting string
    println(arrayString)
}

Output

[apple, banana, orange, kiwi]

Summary

In this tutorial, we’ve covered the contentToString() function in Kotlin arrays, its syntax, and how to use it to obtain a string representation of the content of an array.