Search code examples
arrayskotlinobject-class

How to make static array in Kotlin?


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

Solution

  • 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:

    object Data {
        
        val array = mutableListOf<PersonModel> (PersonModel("roshan",65,50,"White",21,"male"))
        
        init {
            array.add(PersonModel("roshan",65,50,"White",21,"male"))
        }
    }
    

    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() or apply():

    val array = mutableListOf<PersonModel>().apply {
        add(PersonModel("roshan",65,50,"White",21,"male"))
        add(PersonModel("roshan",65,50,"White",21,"male"))
    }
    

    In your specific case, you don't have to do this, because you can create a list with both items directly:

    val array = mutableListOf<PersonModel> (
        PersonModel("roshan",65,50,"White",21,"male"),
        PersonModel("roshan",65,50,"White",21,"male"),
    )