user1865027
user1865027

Reputation: 3647

how to create an array of repeating object in kotlin?

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

Answers (2)

s1m0nw1
s1m0nw1

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

homerman
homerman

Reputation: 3579

the repeat function is another approach:

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) }
}

Upvotes: 6

Related Questions