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?

lannyf
  • 9,865
  • 12
  • 70
  • 152

1 Answers1

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()
hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 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 Aug 07 '18 at 14:28
  • 1
    @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. – hotkey Aug 07 '18 at 14:40
  • My bad, I had defined `BASIC_ESCAPE_RULE` as `Array>`, that's why it was working – user2340612 Aug 07 '18 at 14:48