Reputation: 996
How do I convert Array<String>
to ArrayList<String>
in Kotlin?
var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = ArrayList(Arrays.asList(list))
I receive this error:
Error
Type inference failed. Expected type mismatch: inferred type is kotlin.collections.ArrayList<Array<String>!> /* = java.util.ArrayList<Array<String>!> */ but kotlin.collections.ArrayList<String>? /* = java.util.ArrayList<String>? */ was expected
Upvotes: 11
Views: 12689
Reputation: 508
Hope it'll help.
var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = list.toCollection(ArrayList())
Upvotes: 3
Reputation: 56875
The spread operator and arrayListOf
is another option:
var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = arrayListOf(*list)
Upvotes: 0
Reputation: 31
import kotlin.collections.ArrayList
var arr:List<String>=["one","two"]<br>
val array_list:ArrayList<String>=ArrayList(arr)
Upvotes: -1
Reputation: 12803
Another approach is use arrayListOf
categoryList =arrayListOf("None", "ABC")
Upvotes: 1
Reputation: 23242
You may be interested in toCollection
to add the elements to any collection you pass:
categoryList = list.toCollection(ArrayList())
Note that to fix your specific problem you just need the spread operator (*
). With the *
-fix applied it would have worked too:
categoryList = ArrayList(Arrays.asList(*list))
Upvotes: 20