1

I'm trying to read a list of string from a file, which is structured as a list:

ElemA
ElemB
ElemC

I need to save into this variable, which is defined as:

private var history: Array<out String>?

I made this method, but it doesn't works because it requires an Array? as output, but it founds an Array<(out) Any!>!

private fun loadHistory(): Array<out String>? {
    val list = ArrayList<String>()
    File("history").forEachLine { list.add(it) }
    return list.toArray()
}

How can I solve?

2

1 Answer 1

1

As suggested by @jsamol in the comments.

You should use toTypedArray() instead of toArray() to get an array of the specific type.(ref)

toArray() returns new array of type Array<Any?>. (ref)

private fun loadHistory(): Array<out String>? {
    val list = ArrayList<String>()
    File("history").forEachLine { list.add(it) }
    return list.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.