<@U84KF4UHM> if you want your code reviewed, you g...
# codereview
s
@ecampolo if you want your code reviewed, you gotta put up your attempt to solve the problem
e
Done!
s
Okay!
Is there a reason you’re using
forEach
over
map
or
flatMap
?
e
because if I use flatmap and map i would lose those entries whose array are empty
s
@ecampolo?
e
since map would omit those foo with empty bars
đź‘Ť 1
s
That’s true if you use them in a certain way, but that doesn’t mean they’re not useful to your problem
You’re right that map alone would avoid iterating over empty lists instead of creating a
FooBar
with
null
- in this case I don’t think it’s possible to get away without using some kind of conditional logic
e
that's a shame haha
i was eager to find a one liner with some FP sauce
tried with groupingBy
s
the most succinct snippet I could come up with looks like this
Copy code
foos.flatMap { foo ->
    when {
      foo.bars.isEmpty() -> listOf(FooBar(foo, null))
      else -> foo.bars.map { FooBar(foo, it) }
    }
  }
e
not bad
let me see
the only thing I see is that we are creating multiple arrays
but i dont think is that bad in terms of memory consumption, i will try it
s
unless
n
is huge, I doubt it’ll be too problematic
e
it is quite large
i will test it thou
i like the approach
thank you
đź‘Ť 1
s
a less readable but maybe more efficient approach might look like this:
Copy code
foos.flatMap { foo ->
  (if (foo.bars.isEmpty()) listOf(null) else foo.bars)
      .map { FooBar(foo, it) }
}