18

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.

2 Answers 2

35

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)]
Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.