Reputation: 3647
I know how to do it by creating a loop but I wanted to know if there's an easier way?
for example, I want to create an array of Point
and they will all have (0,0)
or increment x,y
by their index.
Upvotes: 18
Views: 8771
Reputation: 81949
Array
has a special constructor for such things:
/**
* 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)
It can be used for both of your use cases:
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)]
Upvotes: 35