6 Ways to Print an Array in Kotlin with example
Let’s declare an array in Kotlin
val array = arrayOf("a", "b", "c", "d")
Now, print the array using the println
function:
println(array)
The output is:
[Ljava.lang.String;@7cc355be
Inspecting the values of an array during debugging becomes challenging with this output. So, how can you print your Kotlin array object without getting “type@hashcode
?
This tutorial explains how to print the array elements to the console.
How to Print Array Elements in Kotlin with Examples
There are multiple ways to log an array of items in Kotlin.
Use a For Loop
The for in
loop iterates through each element in an array and prints each element to the console using the println
function.
It’s a native and basic way to iterate through each element.
import java.util.Arrays
fun main() {
val array = arrayOf("a", "b", "c", "d")
for (item in array) {
println(item)
}
}
Output:
a
b
c
d
Use Arrays.toString Method
The Arrays
class has a built-in toString
method that takes an array variable and prints its values. It’s an easy way to print without iterating through each element.
import java.util.Arrays
fun main() {
val array = arrayOf("a", "b", "c", "d")
println(Arrays.toString(array))
}
Output
[a, b, c, d]
Use the Array joinToString method
The joinToString
method takes a separator, iterates through each element, appends, and returns the string.
fun main() {
val array = arrayOf("a", "b", "c", "d")
println(array.joinToString(" "))
}
Use the forEach Method
The forEach🔗 method takes a lambda expression.
It iterates through each element, applies a function, and calls the body inside it.
fun main() {
val array = arrayOf("a", "b", "c", "d")
// lambda expression
array.forEach { println(it) }
//using method reference syntax
array.forEach(System.out::print)
}
When the above program prints
a
b
c
d
abcd
Use the Array contentToString Function
The contentToString
function prints the array elements by displaying the string representation of each element.
fun main() {
val array = arrayOf("a", "b", "c", "d")
println(array.contentToString())// [a, b, c, d]
}
How to Print Array of Strings or Integers
Arrays of strings or integers can be printed using the approaches mentioned above.
Here is an example:
fun main() {
val numbers = intArrayOf(11, 12, 13, 14, 15)
println(numbers.contentToString())
}
Outputs:
[11, 12, 13, 14, 15]
Conclusion
This tutorial explored various methods for printing array elements in Kotlin, providing flexibility based on different approaches.
Developers can choose from options such as
- using a for loop for a native approach,
- leveraging
Arrays.toString
for simplicity, - employing
joinToString
for customization, - utilizing
forEach
for lambda expression functionality, - or using
contentToString
for string representation.
The diverse set of methods caters to different needs, allowing developers to select the most suitable approach when working with arrays in Kotlin.