gpt4 book ai didi

arrays - Kotlin 数组初始化函数

转载 作者:行者123 更新时间:2023-12-04 22:56:22 26 4
gpt4 key购买 nike

我是 Kotlin 的新手,很难理解 init function在数组的上下文中工作。具体来说,如果我试图制作 String 的数组键入使用:

val a = Array<String>(a_size){"n = $it"}
  • 这有效,但是"n = $it" 有什么作用?意思?这看起来不像 init函数,因为它在花括号内而不是在括号内。
  • 如果我想要一个 Int 的数组init 会是什么?函数或花括号内的部分是什么样的?
  • 最佳答案

    您正在使用初始化程序调用构造函数:

    /**
    * Creates a new array with 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) -> T)

    因此,您将一个函数传递给构造函数,该函数将为每个元素调用。 a的结果将会
    [
    "n = 0",
    "n = 1",
    ...,
    "n = $a_size"
    ]

    如果您只想创建一个包含所有 0 的数组值,这样做:
    val a = Array<Int>(a_size) { 0 }

    或者,您可以通过以下方式创建数组:
    val a = arrayOf("a", "b", "c")
    val b = intArrayOf(1, 2, 3)

    关于arrays - Kotlin 数组初始化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44325442/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com