Array – Java ArrayList to kotlin array

Is there an easy way to convert a Java ArrayList into a kotlin array? The following codes:

fun test(): Array<String> {
  val elems = ArrayList<String>()
  return elems.toArray()
}

Error given:

main.kt:2:15: error: unresolved reference: ArrayList
  val elems = ArrayList<String>()
              ^

I'm parsing some JSON, and I don't know how many elements to end, but once I read them, I don't need to modify the data in any way, so I thought I would go to kotlin array as the data type

Solution

Why use arrays? Kotlin arrays are mutable, just like Java arrays You should use the kotlin list instead of the mutablelist, which is immutable As for why the code is not compiled: toArray returns an object []. If you want a list string [], you need to use an array version of toArray as a parameter

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>