ecampolo
11/23/2017, 4:19 PMclass Foo(val bars: List<String> = ArrayList())
class FooBar(val foo: Foo, val bar: String?)
fun main(args: Array<String>) {
val foo1 = Foo(listOf("a", "b", "c"))
val foo2 = Foo()
val foo3 = Foo(listOf("d"))
val foo4 = Foo()
val foos = listOf(foo1, foo2, foo3, foo4)
// How can I flat map into a list of:
// FooBar(foo1, "a")
// FooBar(foo1, "b")
// FooBar(foo1, "c")
// FooBar(foo2, null)
// FooBar(foo3, "d")
// FooBar(foo4, null)
// This is actually working but I would like to avoid creating the list a priori and
// remove the conditional
val fooBars: MutableList<FooBar> = ArrayList()
foos.forEach { foo ->
if (foo.bars.isEmpty()) {
fooBars.add(FooBar(foo, null))
} else {
foo.bars.forEach { bar -> fooBars.add(FooBar(foo, bar)) }
}
}
}