Two-dimensional Int array in Kotlin

后端 未结 3 1066
独厮守ぢ
独厮守ぢ 2021-01-01 10:11

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

val board = Array(n, { IntArray(n) })
相关标签:
3条回答
  • 2021-01-01 11:02

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

    0 讨论(0)
  • 2021-01-01 11:05

    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("")
        }
    
    }
    
    0 讨论(0)
  • 2021-01-01 11:06

    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)
    }
    
    0 讨论(0)
提交回复
热议问题