Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an array of repeating object in kotlin?

Tags:

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.

like image 389
user1865027 Avatar asked Dec 22 '17 00:12

user1865027


People also ask

How do I create an array of objects in Kotlin?

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.

How do I create a dynamic array in Kotlin?

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.


2 Answers

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)]
like image 129
s1m0nw1 Avatar answered Sep 18 '22 02:09

s1m0nw1


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) }
}
like image 24
homerman Avatar answered Sep 18 '22 02:09

homerman