Two-dimensional Int array in Kotlin

2019-02-07 20:57发布

问题:

Is it the easiest way to declare two-dimensional Int array with specified size in Kotlin?

val board = Array(n, { IntArray(n) })

回答1:

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)
}


回答2:

Currently this is the easiest way, we will extend the standard library with appropriate functions later



回答3:

Yes, your given code is the easiest way to declare a two-dimensional array.

Below, I am giving you an example of 2D array initialization & printing.

fun main(args : Array<String>) {
    var num = 100

    // Array Initialization
    var twoDArray = Array(4, {IntArray(3)})
    for(i in 0..twoDArray.size - 1) {
        var rowArray = IntArray(3)
        for(j in 0..rowArray.size - 1) {
            rowArray[j] = num++
        }
        twoDArray[i] = rowArray
    }

    // Array Value Printing
    for(row in twoDArray) {
        for(j in row) {
            print(j)
            print(" ")
        }
        println("")
    }

}


标签: arrays kotlin