Kotlin – Print an Array

Print an Array in Kotlin

When we just print the Array object using println() function, it prints the object notation, but not the contents of it.

To print the contents of an Array in Kotlin, you can use built-in println() function along with Array.contentToString() function.

The contentToString() function returns a string with the elements of the Array in the notation of comma separated values enclosed in square brackets, a typical array notation. And we can print this using println() function.

Examples

Print an Array of Strings

In the following program, we take an Array of strings fruitNames, and print its contents to the standard output.

Kotlin Program

fun main(args: Array<String>) {
    val fruitNames = arrayOf("apple", "banana", "cherry")
    println(fruitNames.contentToString())
}

Output

[apple, banana, cherry]

Print an Array of Integers

In the following program, we take an Array of integers squares, and print its contents to the standard output.

Kotlin Program

fun main(args: Array<String>) {
    val squares = arrayOf(1, 4, 9, 16, 25)
    println(squares.contentToString())
}

Output

[1, 4, 9, 16, 25]