本文介绍了Kotlin中的二维Int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中声明具有指定大小的二维Int数组是最简单的方法吗?

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

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

推荐答案

以下是用于创建2D数组的新顶级函数的源代码.当Kotlin缺少某些东西时,请扩展它.然后添加 YouTrack问题,以显示您要建议的内容并跟踪其状态.尽管在这种情况下它们并没有比上面短很多,但至少为正在发生的事情提供了更明显的命名.

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

和用法:

public fun foo() {
    val someArray = array2d<String?>(100, 10) { null }
    val intArray = array2dOfInt(100, 200)
}

这篇关于Kotlin中的二维Int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:19