Convert Array<Any> to Array<Int> in Kotlin
This article explores different ways to convert Array<Any> to Array<Int> in Kotlin.
1. Using map() function
Here, the idea is to convert the array into a list and transform each element into a corresponding int value using the map() function. Finally, return the list as an array using toTypedArray() function.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val src: Array<Any> = arrayOf(4, 3, 5, 2, 8) val dest: Array<Int> = src.toList() .map { i -> i.toString().toInt() } .toTypedArray() println(dest.contentToString()) // [4, 3, 5, 2, 8] } |
2. Using System.arraycopy() function
Another solution is to use the System.arraycopy() to copy an array to another array. This will work fine for arrays of different types when an element in the source array can be stored in the destination array.
|
1 2 3 4 5 6 7 8 |
fun main() { val src: Array<Any> = arrayOf(4, 3, 5, 2, 8) val dest: Array<Int?> = arrayOfNulls(src.size) System.arraycopy(src, 0, dest, 0, src.size) println(dest.contentToString()) // [4, 3, 5, 2, 8] } |
3. Custom Routine
The idea is to iterate over the array using a for-loop and copy every element to an integer array after converting it into its corresponding integer value.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val src: Array<Any> = arrayOf(4, 3, 5, 2, 8) val dest: Array<Int?> = arrayOfNulls(src.size) for (i in src.indices) { dest[i] = src[i] as Int } println(dest.contentToString()) // [4, 3, 5, 2, 8] } |
That’s all about converting an Object array to an Integer 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 :)