Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Cast ArrayList<String!> to Array<String>

Tags:

kotlin

I am trying to split a string that is input by the user. My code looks similar to the following:

val aList = Array(5, {Array<String>(2){ " " }})
aList[0] = ArrayList(input.nextLine().split(" "))  // `split` returns a List

But this results in the following error: error: type inference failed. Expected type mismatch: inferred type is ArrayList<String!> but Array<String> was expected.

After some digging around I found that the T! operator means T or T?. How can I cast ArrayList<String!> to Array<String>?

like image 571
Araf Avatar asked Oct 23 '25 19:10

Araf


1 Answers

ArrayList<T> and Array<T> are completely different types, so, formally speaking, you cannot just make a cast.

You can, however, convert a List<T> to an Array<T> using .toTypedArray():

aList[0] = input.nextLine().split(" ").toTypedArray()
like image 65
hotkey Avatar answered Oct 26 '25 18:10

hotkey