Print an array in Kotlin
This article explores different ways to print an array in Kotlin.
1. Using index-based for-loop
The standard solution to print arrays in Kotlin is using an index-based loop.
|
1 2 3 4 5 6 |
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) for (i in arr.indices) { println(arr[i]) } } |
Output:
1
2
3
4
5
2. Using foreach loop
In Kotlin, you can replace the above index-based for-loop with a foreach loop.
|
1 2 3 4 5 6 |
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) for (value in arr) { println(value) } } |
Output:
1
2
3
4
5
3. Using forEach() function
Alternatively, you can use the forEach() function to print an array.
|
1 2 3 4 |
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) arr.forEach { println(it) } } |
4. Using contentToString() function
Another solution is to simply print the string representation of the contents of the given array. This can be done using the contentToString() function.
|
1 2 3 4 5 |
fun main() { val arr = arrayOf(1, 2, 3, 4, 5) println(arr.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about printing an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)