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

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

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


当前回答

你可以像这样创建一个Int数组:

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

5是Int数组的大小。函数是元素init函数。“it”范围在[0,4],加上1 make范围在[1,5]

原点函数为:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * 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)
  ...
 }

定义在Arrays.kt中的IntArray类

其他回答

在Kotlin中有几种初始化数组的方法:

劳动力素质():

var myarray = arrayOf(1,2,3,4,5)

劳动力素质():

var myarray = arrayOf<Int>(1,2,3,4,5)

使用Array构造函数:

val num = Array(3, {i-> i*1})

内置的工厂方法:

val num1 = intArrayOf(1, 2, 3, 4)
//For Byte Datatype
val num2 = byteArrayOf()
//For Character Datatype
val num3 = charArrayOf()
//For short Datatype
val num4 = shortArrayOf()
//For long
val num5 = longArrayOf()

对于二维数组:

val rows = 3
val cols = 3
val value = 0
val array = Array(rows) { Array<Int>(cols) { value } }

您可以将元素类型更改为您想要的任何类型(String, Class,…),并将值更改为相应的默认值。

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

详见Kotlin -基本类型。

你也可以提供一个初始化函数作为第二个参数:

val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]

您可以使用这些方法

var numbers=Array<Int>(size,init)
var numbers=IntArray(size,init)
var numbers= intArrayOf(1,2,3)

例子

var numbers = Array<Int>(5, { i -> 0 })

Init表示默认值(initialize)

你可以像这样创建一个Int数组:

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

5是Int数组的大小。函数是元素init函数。“it”范围在[0,4],加上1 make范围在[1,5]

原点函数为:

 /**
 * An array of ints. When targeting the JVM, instances of this class are 
 * represented as `int[]`.
 * @constructor Creates a new array of the specified [size], with all elements 
 *  initialized to zero.
 */
 public class IntArray(size: Int) {
       /**
        * 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)
  ...
 }

定义在Arrays.kt中的IntArray类