https://kotlinlang.org logo
Title
h

hho

02/09/2021, 7:32 PM
1️⃣:
val serials = devices.map { it.motor.serial }
2️⃣:
val serials = devices.map(Device::motor).map(Motor::serial)
Is there any reason ever to go with 2️⃣?
1️⃣ 5
j

Joel

02/09/2021, 7:33 PM
Don't forget about
val serials = devices.map { it.motor }.map { it.serial }
!
l

Luke

02/09/2021, 7:41 PM
Keep in mind that, unless you are using
Sequence
, a list is instantiated at each
.map
call. So 1️⃣ is better imo
j

Joel

02/09/2021, 7:41 PM
In my experience, the functional purist would prefer a single transformation at each step (option 2, take your pick of syntax). However it does use more memory since you create another collection under the hood, so as you scale your code gravitates towards option 1. A good example would be a sum:
val totalMileage = devices.map { it.odometer }.sum() // O(n) memory
versus
val totalMileage = devices.fold(0) { acc, d -> acc + d.odometer } // O(1) memory
which is why
.sumBy
exists.
h

hho

02/10/2021, 1:21 AM
Thanks to all of you!