如何在kotlin中创建重复对象数组?
我知道如何创建循环,但我想知道是否有更简单的方法 例如,我想创建一个如何在kotlin中创建重复对象数组?,kotlin,Kotlin,我知道如何创建循环,但我想知道是否有更简单的方法 例如,我想创建一个点数组,它们都有(0,0)或按索引递增x,y 该功能是另一种方法: data class Point(val x: Int, val y: Int) @Test fun makePoints() { val size = 100 val points = arrayOfNulls<Point>(size) repeat(size) { index -> points[index]
点
数组,它们都有(0,0)
或按索引递增x,y
该功能是另一种方法:
data class Point(val x: Int, val y: Int)
@Test fun makePoints() {
val size = 100
val points = arrayOfNulls<Point>(size)
repeat(size) { index -> points[index] = Point(index,index) }
}
数据类点(val x:Int,val y:Int)
@测试乐趣要点(){
val大小=100
val points=阵列数量(大小)
重复(大小){index->points[index]=Point(index,index)}
}
数组
有一个特殊的构造函数来处理这样的事情:
/**
* Creates a new array with 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) -> T)
它可以用于您的两个用例:
val points = Array(5) {
Point(0, 0)
}
//[Point(x=0, y=0), Point(x=0, y=0), Point(x=0, y=0), Point(x=0, y=0), Point(x=0, y=0)]
val points2 = Array(5) { index->
Point(index, index)
}
//[Point(x=0, y=0), Point(x=1, y=1), Point(x=2, y=2), Point(x=3, y=3), Point(x=4, y=4)]