在Java中,数组可以这样初始化:

int numbers[] = new int[] {10, 20, 30, 40, 50}

Kotlin的数组初始化是怎样的?


当前回答

当初始化下面的字符串检查

val strings = arrayOf("January", "February", "March")

我们可以使用原始int数组专用的arrayOf方法简单地初始化它:

val integers = intArrayOf(1, 2, 3, 4)

其他回答

你可以简单地使用现有的标准库方法,如下所示:

val numbers = intArrayOf(10, 20, 30, 40, 50)

使用一个特殊的构造函数可能是有意义的:

val numbers2 = IntArray(5) { (it + 1) * 10 }

你传递一个大小和一个lambda来描述如何初始化这些值。以下是文档:

/**
 * Creates a new array of the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> Int)

在我的情况下,我需要初始化我的抽屉项目。我通过以下代码填充数据。

    val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
    val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)


    // Use lambda function to add data in my custom model class i.e. DrawerItem
    val drawerItems = Array<DrawerItem>(iconsArr.size, init = 
                         { index -> DrawerItem(iconsArr[index], names[index])})
    Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)

自定义模型类-

class DrawerItem(var icon: Int, var name: String) {

}

I think one thing that is worth mentioning and isn't intuitive enough from the documentation is that, when you use a factory function to create an array and you specify it's size, the array is initialized with values that are equal to their index values. For example, in an array such as this: val array = Array(5, { i -> i }), the initial values assigned are [0,1,2,3,4] and not say, [0,0,0,0,0]. That is why from the documentation, val asc = Array(5, { i -> (i * i).toString() }) produces an answer of ["0", "1", "4", "9", "16"]

当初始化下面的字符串检查

val strings = arrayOf("January", "February", "March")

我们可以使用原始int数组专用的arrayOf方法简单地初始化它:

val integers = intArrayOf(1, 2, 3, 4)

我想知道为什么没有人给出最简单的答案:

val array: Array<Int> = [1, 2, 3]

根据对我最初答案的一个评论,我意识到这只在注释参数中使用时才有效(这对我来说真的是出乎意料)。

看起来Kotlin不允许在注释之外创建数组文字。

例如,使用args4j库中的@Option查看以下代码:


    @Option(
        name = "-h",
        aliases = ["--help", "-?"],
        usage = "Show this help"
    )
    var help: Boolean = false

选项参数“aliases”的类型是Array<String>