:one:: ```val serials = devices.map { it.motor.ser...
# codereview
h
1️⃣:
Copy code
val serials = devices.map { it.motor.serial }
2️⃣:
Copy code
val serials = devices.map(Device::motor).map(Motor::serial)
Is there any reason ever to go with 2️⃣?
1️⃣ 5
j
Don't forget about
val serials = devices.map { it.motor }.map { it.serial }
!
l
Keep in mind that, unless you are using
Sequence
, a list is instantiated at each
.map
call. So 1️⃣ is better imo
j
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:
Copy code
val totalMileage = devices.map { it.odometer }.sum() // O(n) memory
versus
Copy code
val totalMileage = devices.fold(0) { acc, d -> acc + d.odometer } // O(1) memory
which is why
.sumBy
exists.
h
Thanks to all of you!