Did I imagine it, or is there some way to build a ...
# announcements
l
Did I imagine it, or is there some way to build a list using the Function literals with receiver, like typesafe DSLs do, so you can do something like this:
Copy code
val myList = listOf {
    add("Blah")
    add("Foo")
    if(somethingIsTrue) {
         add("More")
         add("Stuff")
    }
}
I seem to remember somebody talking about it, or tweeting about it? Possibly it was coming to the standard libraries?
t
I think that this is a future addition to the stdlib. It should be named
buildList
.
c
you could do something like this:
Copy code
val myList = sequence {
	yield("Blah")
	yield("Foo")
	if (somethingIsTrue) {
		yield("More")
		yield("Stuff")
	}
}.toList()
I'm not sure how significant SequenceBuilder overhead will be though. There's also the obvious:
Copy code
val myList = mutableListOf<String>().apply {
	add("Blah")
	add("Foo")
	if(somethingIsTrue) {
		add("More")
		add("Stuff")
	}
}.toList()
👍 3
s
I’d put the fixed elements directly into the mutable list generation
Copy code
val myList = mutableListOf<String>(
	"Blah",
	"Foo"
).apply {
	if(somethingIsTrue) {
		add("More")
		add("Stuff")
	}
}.toList()
l
Ahh! turns out I didn't imagine it. It was actually linked to over in #C4GKV43N2 in this slack! https://youtrack.jetbrains.com/issue/KT-15363#focus=streamItem-27-1910045.0-0