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.
Creating an array – There are two ways to define an array in Kotlin. We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array.
ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as pre requisites. It also provide read and write functionalities. ArrayList may contain duplicates and is non-synchronized in nature.
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)]
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) }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With