在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
当前回答
值得一提的是,当使用kotlin内置程序(例如intArrayOf(), longArrayOf(), arrayOf()等)时,对于给定的大小,您不能使用默认值(或所有值为所需值)初始化数组,相反,您需要通过根据类构造函数调用来进行初始化。
// Array of integers of a size of N
val arr = IntArray(N)
// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }
其他回答
你可以简单地使用现有的标准库方法,如下所示:
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)
您可以使用这些方法
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)
在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
但是在Kotlin中,数组初始化的方式有很多,比如:
任何泛型类型的数组都可以使用arrayOf()函数:
val arr = arrayOf(10, 20, 30, 40, 50)
val genericArray = arrayOf(10, "Stack", 30.00, 40, "Fifty")
使用Kotlin的实用函数可以初始化数组
val intArray = intArrayOf(10, 20, 30, 40, 50)
值得一提的是,当使用kotlin内置程序(例如intArrayOf(), longArrayOf(), arrayOf()等)时,对于给定的大小,您不能使用默认值(或所有值为所需值)初始化数组,相反,您需要通过根据类构造函数调用来进行初始化。
// Array of integers of a size of N
val arr = IntArray(N)
// Array of integers of a size of N initialized with a default value of 2
val arr = IntArray(N) { i -> 2 }
你可以像这样创建一个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类