s1m*_*nw1 19
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)
Run Code Online (Sandbox Code Playgroud)
它可以用于两个用例:
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)]
Run Code Online (Sandbox Code Playgroud)
在重复功能是另一种方法:
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) }
}
Run Code Online (Sandbox Code Playgroud)