Kotlin - Can the minimum distance between a location and a list of locations be found with a one liner?

Viewed 44

I would like the following "pseudocode" to be valid syntax (but clearly it's not) :

minDistance = minOf(myLocations.forEach{return location.distanceTo(it)})

To clarify, I am trying to find the distance from the smartphone (location) to the closest location in a mutable list of locations (myLocations).

Does Kotlin allow this level of terseness, or must I break it up in a few more lines and help variables?

1 Answers

I believe this is what you're looking for

minDistance =  myLocations.minOf { location.distanceTo(it) }

Additional info: If you want the location with the shortest distance instead, then you can use

myLocations.minByOrNull { location.distanceTo(it) }
Related