is there a better way to write this? : `users = li...
# codereview
c
is there a better way to write this? :
users = listOf("klaus", "sepperl")+if (addChris) listOf("chris") else listOf()
l
You can use `buildList`:
Copy code
users = buildList {
    addAll("klaus", "sepperl")
    if (addChris) add("chris")
}
c
thanks! thats more performant for sure. but also a bit verbose
z
Is it?
else listOf()
is pretty verbose too. And i think it’s dangerous to try to minimize “verbosity”. It’s much more important to maximize readability, and sometimes going too far down the verbosity route can make code harder to read. The
buildList
code is extremely readable imo. There’s zero code there that doesn’t express something relevant about what it’s doing.
c
its way better than my version for sure.
for some reason i would just prefer
users= buildList("klaus", "sepperl") { if (addChris) add("chris") }
@Zach Klippenstein (he/him) [MOD] btw, “also a bit verbose” meant “also like the original example”
l
Well... You could also do:
Copy code
users = mutableListOf("klaus", "sepperl").apply {
    if (addChris) add("chris")
} // .toList() if you want a read-only list
i
Copy code
listOfNotNull("klaus", "sepperl", "chris".takeIf { addChris})
👍 1
🎉 1
c
thats pretty cool