在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
在Java中,数组可以这样初始化:
int numbers[] = new int[] {10, 20, 30, 40, 50}
Kotlin的数组初始化是怎样的?
当前回答
通过这种方式,可以在koltin中初始化int数组。
val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)
其他回答
你可以试试这个:
var a = Array<Int>(5){0}
在全局声明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)
}
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"]
初始化数组:val paramValueList: array <String?> = arrayOfNulls<String>(5)
在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。