so I am trying to add a list of items to a list, t...
# getting-started
o
so I am trying to add a list of items to a list, there’s 1 item that I would like to either add (or not add) according to some flag
I would like to be able to do it in 1 go, like
Copy code
list.addAll(item1, item2, if (flag) item3))
something along those lines, I know it isnt the way to do it but is there an actual way
r
Copy code
list.addAll(listOfNotNull(item1, item2, if (flag) item3 else null))
But don’t do that.
j
There are several options, but it depends on the bigger picture. You said you wanted to add a list of items. Is it an actual
List
? Because in the snippet you showed it seems you have several variables but not a list to add. Also, why are you using a mutable list in the first place here? Are you interacting with the mutable list long term? Or is it a temporary object that is then just used as a
List
? If the latter,
buildList { ... }
would likely be more appropriate.
y
In fact you could even use
takeIf
Copy code
list.addAll(listOfNotNull(..., item3.takeIf { flag }))
But probably the recommended, and cheaper way to do this is with `buildList`:
Copy code
buildList(3) { // 3 is the maximum size of things you're going to add
  add(item1)
  add(item2)
  if(flag) add(item3)
}
o
nice!
buildList is it! thanks a lot