我知道如何通过创建循环来实现它,但我想知道是否有更简单的方法?
例如,我想创建一个Point
的数组,它们的索引都会(0,0)
或增加x,y
。
答案 0 :(得分:16)
Array
有一个特殊的构造函数用于此类事情:
/**
* 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)]
答案 1 :(得分:4)
repeat函数是另一种方法:
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) }
}