Kotlin: Cast ArrayList <String!> To Array <String>
I am trying to split a string entered by the user. My code looks something like this:
val aList = Array(5, {Array<String>(2){ " " }})
aList[0] = ArrayList(input.nextLine().split(" ")) // `split` returns a List
But this leads to the following error:
error: type inference failed. Expected type mismatch: inferred type is ArrayList<String!> but Array<String> was expected
.
After some digging, I discovered what the operator T!
means T or T?
. How can I cast ArrayList<String!>
up Array<String>
?
source to share
ArrayList<T>
and Array<T>
are completely different types , so technically speaking, you can't just cast.
You can convert List<T>
to Array<T>
with .toTypedArray()
:
aList[0] = input.nextLine().split(" ").toTypedArray()
source to share