Home > Blockchain >  Kotlin - Can the minimum distance between a location and a list of locations be found with a one lin
Kotlin - Can the minimum distance between a location and a list of locations be found with a one lin

Time:05-25

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?

CodePudding user response:

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