Convert an IntArray to an array of Int using Kotlin
This article explores different ways to convert an IntArray to Array<Int> using Kotlin.
1. Using for loop
The idea is to create an array of Int type and assign values to it from the given IntArray using a for-loop.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val ints: IntArray = intArrayOf(1, 2, 3, 4, 5) val array: Array<Int?> = arrayOfNulls(ints.size) for (i in ints.indices) { array[i] = Integer.valueOf(ints[i]) } println(array.contentToString()) // [1, 2, 3, 4, 5] } |
2. Convert To List
Another solution is to convert the specified IntArray to a list using the toList() function. Then, we can call toTypedArray() function to get an Array<Int>.
|
1 2 3 4 5 6 |
fun main() { val ints: IntArray = intArrayOf(1, 2, 3, 4, 5) val array: Array<Int?> = ints.toList().toTypedArray() println(array.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about converting an IntArray to an array of Int using 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 :)