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

Shawn

11/23/2017, 7:42 PM
@ecampolo if you want your code reviewed, you gotta put up your attempt to solve the problem
e

ecampolo

11/23/2017, 7:47 PM
Done!
s

Shawn

11/23/2017, 7:52 PM
Okay!
Is there a reason you’re using
forEach
over
map
or
flatMap
?
e

ecampolo

11/23/2017, 7:56 PM
because if I use flatmap and map i would lose those entries whose array are empty
s

Shawn

11/23/2017, 7:56 PM
@ecampolo?
e

ecampolo

11/23/2017, 7:56 PM
since map would omit those foo with empty bars
👍 1
s

Shawn

11/23/2017, 7:57 PM
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

ecampolo

11/23/2017, 7:59 PM
that's a shame haha
i was eager to find a one liner with some FP sauce
tried with groupingBy
s

Shawn

11/23/2017, 8:03 PM
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

ecampolo

11/23/2017, 8:03 PM
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

Shawn

11/23/2017, 8:06 PM
unless
n
is huge, I doubt it’ll be too problematic
e

ecampolo

11/23/2017, 8:07 PM
it is quite large
i will test it thou
i like the approach
thank you
👍 1
s

Shawn

11/23/2017, 8:11 PM
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) }
}
4 Views