Given a complex object like the following:
case class Complex
(
id: Long,
name: String,
nested: Seq[Complex]
)
In action this can turn into something like this:
val stuff =
List(
Complex(1, "name1",
List(
Complex(2, "name2", List()),
Complex(3, "name3",
List(
Complex(4, "name4", List())
)
)
)
)
)
I need to turn it into a flat list of Complex objects, pulling all the children/grandchildren up.
val flattened =
List(
Complex(1, "name1", List()),
Complex(2, "name2", List()),
Complex(3, "name3", List()),
Complex(4, "name4", List()),
)
Do you have any leads/ideas on how I can accomplish this?
The other solutions I have tried seem to only do simple nesting of lists. Things I've tried:
These all seem to yield the same list I started with.
The difficulty in flattening of the input Seq here is that it is necessary to remove the nested references in the resulting list. This can be done by copying the original object with nested = empty list and flattening all the sequences:
def flatten(obj: Complex): Seq[Complex] = {
val unnested = obj.copy(nested = List())
Seq(unnested) ++ obj.nested.flatMap(flatten)
}
println(stuff.flatMap(flatten))
List(
Complex(1,name1,List()),
Complex(2,name2,List()),
Complex(3,name3,List()),
Complex(4,name4,List())
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With