Is there a simple way of converting a Java ArrayList to a Kotlin Array? The following code:
fun test(): Array<String> { val elems = ArrayList<String>() return elems.toArray() }
gives the error:
main.kt:2:15: error: unresolved reference: ArrayList val elems = ArrayList<String>() ^
I'm parsing some JSON and don't know how many elements I'm going to end up with, but once I've read them I don't need to modify the data in any way so I thought I'd go with Kotlin arrays as the data type.
In this example, we will see how we can define an ArrayList in Kotlin and add an item in the list. We can do it using the library function add() or we can use the "+=" operator. In order demonstrate, we will be creating two ArrayLists, one is of mutable type and the other is of immutable type.
In Kotlin, the default implementation of List is ArrayList which you can think of as a resizable array.
ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as pre requisites. It also provide read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature.
In this program, you'll learn to convert a list to an array using toArray () and array to list using asList () in Kotlin. In the above program, we have defined an array list, vowels_list . To convert the array list to an array, we have used the toTypedArray () method. Finally, the elements of the array are printed by using the forEach () loop.
Learn to convert ArrayList to array using toArray () method with example. toArray () method returns an array containing all of the elements in the list in proper sequence (from first to last element). 1. ArrayList toArray () syntax
You should use a Kotlin List, which as opposed to MutableList, is immutable. As to why the code doesn't compile: toArray returns an Object[], if you want a String[] from a List you need to use the toArray version that takes an Array as it's argument. Kotlin's List is a perfect choice for the job.
1. ArrayList toArray () syntax toArray () is overloaded method and comes in two forms: The first method does not accept any argument and returns the array of object type. We must iterate the objects array to find the desired element and typecast to desired class type.
Try to use extension function toTypedArray
, like:
fun test(): Array<String> { val elems = arrayListOf<String>() return elems.toTypedArray() }
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