https://kotlinlang.org logo
#codereview
Title
# codereview
c

christophsturm

03/31/2021, 2:24 PM
is there a better way to write this? :
users = listOf("klaus", "sepperl")+if (addChris) listOf("chris") else listOf()
l

Luke

03/31/2021, 2:30 PM
You can use `buildList`:
Copy code
users = buildList {
    addAll("klaus", "sepperl")
    if (addChris) add("chris")
}
c

christophsturm

03/31/2021, 2:37 PM
thanks! thats more performant for sure. but also a bit verbose
z

Zach Klippenstein (he/him) [MOD]

03/31/2021, 3:08 PM
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

christophsturm

03/31/2021, 3:17 PM
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

Luke

03/31/2021, 5:24 PM
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

ilya.gorbunov

04/01/2021, 4:15 PM
Copy code
listOfNotNull("klaus", "sepperl", "chris".takeIf { addChris})
👍 1
🎉 1
c

christophsturm

04/01/2021, 4:16 PM
thats pretty cool
4 Views