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
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))
Hope it'll help.
var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = list.toCollection(ArrayList())
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