What is the Kotlin way of printing IntArray contents?

Viewed 2036

What is the Kotlin way of printing IntArray contents?

class Solution {
    fun plusOne(digits: IntArray): IntArray {

        println(digits.toString()) // does not work
        println(Arrays.toString(digits)) // does work but its java way of doing
        for(i in 0 until digits.size) {
           ...
        }

        return digits
    }
}

Is there any kotlin method which works similar to Arrays.toString() ? I just want to see the content for debugging purpose.

5 Answers

There are multiple ways, depending on your requirement, you can use any. Note that you don't have to convert it to List just to print, unless you need it for other use cases.

println(arr.contentToString())

//this one prints number on each line
arr.forEach(::println)  // same as arr.forEach{println(it)}

You can also use Arrays.toString but contentToString() is convenient, and it internally calls Arrays.toString

You can use the contentToString function available for all types of Array

val digits = intArrayOf(1,2,3,4)

val javaToString = Arrays.toString(digits).also(::println)    // [1, 2, 3, 4]
val kotlinToString = digits.contentToString().also(::println) // [1, 2, 3, 4]
println(javaToString == kotlinToString)                       // true

Here is a working example https://pl.kotl.in/dUu_aioq0

After doing a bit more research, I wanted to add joinToString() to above awesome answers :

val numbers = intArrayOf(1, 2, 3, 4, 5, 6)
println(numbers.joinToString()) 

This will print below output :

1, 2, 3, 4, 5, 6

This also allows you add prefix, suffix of your choice as below :

println(numbers.joinToString(prefix = "{", postfix = "}"))

This would output :

{1, 2, 3, 4, 5, 6}

There are many ways to accomplish it. One way would be to first build the output string using fold and then print it inside an also function:

val digits = intArrayOf(1,2,3,4,5,6,7)

digits.fold("[") { output, item -> "$output $item" }.also { println("$it ]") }

This would output:

[ 1 2 3 4 5 6 7 ]

Try to convert to list

fun main() {
    val digits: IntArray = IntArray(10)
    println(digits.toList())  // or digits.asList()
}

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Related