在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
当前回答
对于二维数组:
val rows = 3
val cols = 3
val value = 0
val array = Array(rows) { Array<Int>(cols) { value } }
您可以将元素类型更改为您想要的任何类型(String, Class,…),并将值更改为相应的默认值。
其他回答
你可以像这样创建一个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类
老问题了,但如果你想使用一个范围:
var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()
产生几乎相同的结果:
var numbers = Array(5, { i -> i*10 + 10 })
结果:10,20,30,40,50
我认为第一个选项更有可读性。这两个工作。
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
详见Kotlin -基本类型。
你也可以提供一个初始化函数作为第二个参数:
val numbers = IntArray(5) { 10 * (it + 1) }
// [10, 20, 30, 40, 50]
在Kotlin中有几种方法。
var arr = IntArray(size) // construct with only size
然后从用户或其他集合或任何你想要的地方获取初始值。
var arr = IntArray(size){0} // construct with size and fill array with 0
var arr = IntArray(size){it} // construct with size and fill with its index
我们也可以用内置函数创建数组,比如-
var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values
另一种方式
var arr = Array(size){0} // it will create an integer array
var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.
你也可以使用doubleArrayOf()或DoubleArray()或任何基本类型来代替Int。
简单的方法:
整数:
var number = arrayOf< Int> (10,20,30,40,50)
保持所有数据类型
var number = arrayOf(10, "string value", 10.5)