4

From one library module it returns some Array<Array<String>>, like below:

private val BASIC_ESCAPE_RULE = arrayOf(arrayOf("\"", "&quot;"), // " 
        arrayOf("&", "&amp;"), 
        arrayOf("<", "&lt;"), 
        arrayOf(">", "&gt;"))


fun getBasicEscapeRule(): Array<Array<String>> {
    return BASIC_ESCAPE_RULE.clone()
}

In the project it has dependency on that library and it also uses another library module to do lookup/translation, which only takes Array<CharSequence>.

class translator (vararg lookup: Array<CharSequence>) {

     ... ...
     fun translate(content: String) : String {}
}

When trying to call into a the second library's routing with the data getting from the first library, the making of the translator translator(*getBasicEscapeRule()) got error:

Type mismatch: inferred type is Array<Array<String>> but Array<out Array<CharSequence>> was expected

In the second library it needs to use CharSequence for char manipulation.

How to convert the Array into Array?

1 Answer 1

3

To transform an Array<Array<String>> into an Array<Array<CharSequence>>, you can use the following code:

val src: Array<Array<String>> = TODO()

val result: Array<Array<CharSequence>> = 
    src.map { array -> array.map { s -> s as CharSequence }.toTypedArray() }.toTypedArray()
Sign up to request clarification or add additional context in comments.

3 Comments

Actually you don't need the as CharSequence as the compiler should automatically infer the type for you, but it might be better to keep it for clarity
@user2340612, well, omitting as CharSequence leads to a type mismatch. Seems like the compiler cannot infer the right upcast (String to CharSequence) from the expected type.
My bad, I had defined BASIC_ESCAPE_RULE as Array<Array<out CharSequence>>, that's why it was working

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.