Hi everyone! I have a list of locations, and am ...
# getting-started
m
Hi everyone! I have a list of locations, and am trying to calculate the total distance for a route moving from the first location through every location to the last. The Location-class has a method distanceTo(location: Location) that I can use for each pair of locations to get the distance. I'm trying to do this for the entire list. I solved this with List.foldIndexed(), because I can use the index to access the next element in the list:
Copy code
val totalDistance = locations.foldIndexed(0.0) { index, distance, from ->
            if (index < locations.size - 1) {
                val to = locations[index + 1]
                distance + from.distanceTo(to)
            } else {
                distance
            }
        }
This doesn't seem very nice to me. I have to call the list outside the scope of the block, and I have to check that I am not at the last element in the list. Do you have any ideas for a better way to do this? Possibly, I should write my own extension method for the List, that allowed me to do something like below, but I don't know if something similar already exists?
Copy code
val totalDistance = locations.sumBy { (from, to) ->
            from.distanceTo(to)
        }