Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to create a 2D Array of the type String

Tags:

arrays

kotlin

2d

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

like image 350
shikhar623 Avatar asked Dec 14 '22 20:12

shikhar623


1 Answers

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
like image 54
hotkey Avatar answered Dec 31 '22 14:12

hotkey