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

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

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


当前回答

在全局声明int array

var numbers= intArrayOf()

方法用value初始化数组

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //create your int array here
    numbers= intArrayOf(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)

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

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

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

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

在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()

在Kotlin中,我们可以使用arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf()函数来创建数组。

例如:

var Arr1 = arrayOf(1,10,4,6,15)  
var Arr2 = arrayOf<Int>(1,10,4,6,15)  
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")  
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")  
var Arr5: IntArray = intArrayOf(5,10,15,20)  

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"]