I want to have a class that stores three sets of 30 Foos each. I can declare them as arrays of Foo but I don't know how I can initialize them (give them default values) with 30 elements.
data class Container (
val first: Array<Foo>,
val second: Array<Foo>,
val third: Array<Foo>,
)
data class Foo (val a: Int, val b: Int)
CodePudding user response:
There aren't too many ways to create an array in Kotlin and they are pretty straightforward. Depending on your needs, you can either use arrayOf() function, Array() constructor or create List
first and then convert it into array.
Example with arrayOf()
:
val first = arrayOf(
Foo(0, 0),
Foo(1, 1),
...
)
Array()
:
val first = Array(30) { Foo(it, it) }
List:
val firstList = mutableListOf<Foo>()
firstList = Foo(0, 0)
firstList = Foo(1, 1)
...
first = firstList.toTypedArray()
If the code for generating these arrays is complicated, you can write it inside init {}
block or create static function(s) that provides these arrays.