4

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

1 Answer 1

12

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.