Home > Software design >  Kotlin mutableListOf with several entries
Kotlin mutableListOf with several entries

Time:11-09

I want to to fill a list with several entries. So far I only have one entry:

val someAttributes: List<Product.MyAttribute> = mutableListOf(Product.MyAttribute("ATTRIBUTE A", listOf("3")))

This is MyAttribute:

  data class MyAttribute(
    var key: String = "",
    var values: List<String> = ArrayList()
  )

What's the correct syntax in Kotlin to add several entries to a mutableList?

CodePudding user response:

val someAttributes = mutableListOf(
  Product.MyAttribute("ATTRIBUTE A", listOf("3")),
  Product.MyAttribute("ATTRIBUTE B", listOf("4")),
  Product.MyAttribute("ATTRIBUTE C", listOf("5"))
)

CodePudding user response:

Use add for a single item, or addAll if you have several. You can pass in an index to say where you want them inserted, otherwise they're added to the end of the list

someAttributes.add(newAttr)
someAttributes.addAll(listOf(coolAttr, radAttr))

If you just want to add them all when you initialise the list, just pass them all in as parameters - mutableListOf takes a vararg, i.e. a variable number of arguments (you just separate them with commas)

someAttributes = mutableListOf(attr1, attr2, attr3)
  • Related