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.
Kotlin print is one of the methods and it is used to print the statement it prints all the user datas and everything inside it onto the screen when we use the println() method and then it prints the statement appends with a newline at the end of the output the printing variable is much as easy compare than the other ...
IntArray in Kotlin IntArray is a class in Kotlin representing the array of elements. Each instance of this class is represented as an integer array. To the constructor of this class you need to pass the number of elements you need in the array (size).
Kotlin Print Functions To output something on the screen the following two methods are used: print() println()
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With