0

Having a two demential string array and the row has only two items,

i.e. {{"1", "a"} {"2", "b"}, {"3", "c"} ... ...}

the invert function to do the invert

public static String[][] invert(final String[][] array) {
    final String[][] newarray = new String[array.length][2];
    for(int i = 0; i<array.length; i++) {
        newarray[i][0] = array[i][1];
        newarray[i][1] = array[i][0];
    }
    return newarray;
}

translate to kotlin:

  1. fun invert(array: Array<Array<String?>>): Array<Array<String?>> {
        val newarray = Array<Array<String?>>(array.size) { arrayOfNulls(2) }
        for (i in array.indices) {
            newarray[i][0] = array[i][1]
            newarray[i][1] = array[i][0]
        }
        return newarray
    }
    

Because of the arrayOfNulls(2), has to define the two demential array to be Array<Array<String?>>

but the return type of Array<Array<String?>> breaks the a lot of the code which expecting Array<Array<String>>

  1. Using the val newarray = Array<Array<String>>(array.size) { Array<String>(2) {""}} to force the array initialized all rows with empty string (so not null).

    fun invert(array: Array<Array<String>>): Array<Array<String>> {
        val newarray = Array<Array<String>>(array.size) { Array<String>(2) {""}}
        for (i in array.indices) {
            newarray[i][0] = array[i][1]
            newarray[i][1] = array[i][0]
        }
        return newarray
    }
    

Is it the only way, or is there some function like

fun strinagArrayOf(vararg elements: String): Array<String>
lannyf
  • 9,865
  • 12
  • 70
  • 152

1 Answers1

3

That translation threw you off the track; there's no reason to initialize and loop again through the fields.

This is signature of constructor you're using:

/**
 * Creates a new array with the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> T)

You actually get to pass you own initialization logic for each item in the init function. You even get index of item you're initializing (it's the only argument so it's not explicitly declared but it's accesible as it).

So to get what you need, You can simply initialize inverted array right there (changed param from array to input for readability):

fun invert(input: Array<Array<String>>) = Array(input.size) {arrayOf(input[it][1], input[it][0]) }
Pawel
  • 15,548
  • 3
  • 36
  • 36