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>?
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()
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