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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With