Is it the easiest way to declare two-dimensional Int
array with specified size in Kotlin?
val board = Array(n, { IntArray(n) })
Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value. To create an array, use the arrayOf() function, and place the values in a comma-separated list inside it: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
There are two ways to define an array in Kotlin. We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array.
Here are source code for new top-level functions to create 2D arrays. When Kotlin is missing something, extend it. Then add YouTrack issues for things you want to suggest and track the status. Although in this case they aren't much shorter than above, at least provides a more obvious naming for what is happening.
public inline fun <reified INNER> array2d(sizeOuter: Int, sizeInner: Int, noinline innerInit: (Int)->INNER): Array<Array<INNER>> = Array(sizeOuter) { Array<INNER>(sizeInner, innerInit) } public fun array2dOfInt(sizeOuter: Int, sizeInner: Int): Array<IntArray> = Array(sizeOuter) { IntArray(sizeInner) } public fun array2dOfLong(sizeOuter: Int, sizeInner: Int): Array<LongArray> = Array(sizeOuter) { LongArray(sizeInner) } public fun array2dOfByte(sizeOuter: Int, sizeInner: Int): Array<ByteArray> = Array(sizeOuter) { ByteArray(sizeInner) } public fun array2dOfChar(sizeOuter: Int, sizeInner: Int): Array<CharArray> = Array(sizeOuter) { CharArray(sizeInner) } public fun array2dOfBoolean(sizeOuter: Int, sizeInner: Int): Array<BooleanArray> = Array(sizeOuter) { BooleanArray(sizeInner) }
And usage:
public fun foo() { val someArray = array2d<String?>(100, 10) { null } val intArray = array2dOfInt(100, 200) }
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