Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array<String> to ArrayList<String>

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
like image 907
AI. Avatar asked Apr 01 '19 08:04

AI.


2 Answers

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))
like image 183
Roland Avatar answered Oct 23 '22 03:10

Roland


Hope it'll help.

var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = list.toCollection(ArrayList())
like image 29
Md. Arif Avatar answered Oct 23 '22 01:10

Md. Arif