I am trying to make a static array in Kotlin. For doing this, I created an Object class, and inside that declared a mutableListOf<PersonModel>()
.
When I try to add new Object PersonModel
to array, I get red underline suggesting error in last line, which says Expecting member declaration
.
Code
object Data {
val array = mutableListOf<PersonModel> (PersonModel("roshan",65,50,"White",21,"male"))
array.add(PersonModel("roshan",65,50,"White",21,"male"))
}
You can't use arbitrary executable code inside object/class declaration. This code block is only for defining of class members. If you want to execute some code when the class is instantiated, you can use initialization block:
If you prefer to keep initialization code for a member in a single place, a common pattern is to use scope function, for example
run()
orapply()
:In your specific case, you don't have to do this, because you can create a list with both items directly: