6

i am learning kotlin. i need to create a 2D array which can hold words , special chars and numbers .some where i found this piece of code THIS The problem with this is that it can hold only Int . When i tried replacing keyword "IntArray" with "string". it returned an error ERROR Can someone help me create a 10x8 Arrray which can hold strings in Kotlin

shikhar623
  • 79
  • 1
  • 2

3 Answers3

11

There's no StringArray in Kotlin (here's an explanation why), use Array<String> instead.

If you can provide the array items as you create the arrays, then creating the array can be done as:

val result = Array(10) { i ->
    Array(8) { j -> 
        "the String at position $i, $j" // provide some initial value based on i and j
    }
}

println(result[0][3]) // Prints: the String at position 0, 3

Otherwise, you can either use some default String value:

val result = Array(10) { Array(8) { "" } }

Or create the inner arrays filled with null values (note: you will have to deal with nullability, you won't be able to use the items as non-null values):

val result = Array(10) { arrayOfNulls<String>(8) } // The type is `Array<Array<String?>>
result[0][0] = "abc"
println(result[0][0]!!.reversed()) // Without `!!`, the value is treated as not-safe-to-use
hotkey
  • 140,743
  • 39
  • 371
  • 326
3

You can also use Array<Array<String>>. Note that the compiler can automatically infer this type, but specifying the type may help you understand better what's going on. Here is an example with output:

fun main() {
    // Create the 2D array of Strings
    val string2DArray: Array<Array<String>> = arrayOf(
        arrayOf("apple", "orange", "avocado", "mango", "banana"),
        arrayOf("_", "!", ":", "?"),
        arrayOf("1", "2", "3", "4", "5", "10"))

    // Print the 2D array
    string2DArray.forEach {
        it.forEach { it -> print("$it, ") }
        println()
    }

    // Access an individual String using index notation.
    println("My favorite fruit is: ${string2DArray[0][2]}")
}

Output:

apple, orange, avocado, mango, banana,
_, !, :, ?,
1, 2, 3, 4, 5, 10,

My favorite fruit is: avocado
Cherif Diallo
  • 311
  • 2
  • 3
0

When you convert Java codes to Kotlin, sometimes IDE cannot convert it the way it is expected. Most the of the time I got code as

Array(x) { arrayOf(ArrayList<String>(y)) }

but this code always throw ArrayIndexOutOfBoundsException exception such as

java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

So as @hotkey suggested you can use below approach which is also worked for me;

Array(x) { Array(y) { ArrayList<String>(y) } }
Ercan
  • 2,601
  • 22
  • 23