Search code examples
kotlincharsequence

in kotlin how to change to Array<CharSequence> from Array<String>


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?


Solution

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