What Scala function replaces this procedural statement?

Mindblock is here, but I can't figure out how to make this less ugly:

def getClosestSphere(ray: Ray, spheres: List[Sphere]): Sphere = { val map = new HashMap[Double, Sphere] for (sphere <- spheres) { val intersectPoint = sphere.intersectRay(ray) map.put(intersectPoint, sphere) } map.minBy(_._1)._2 } 

Do you see what I'm doing? I have a list of spheres where each Sphere has an intersectRay method, returning double.

I want to take the sphere with the smallest result of this function. I KNOW that there is a good functional construction that allows me to do this on one line, I just do not see it :(

+4
source share
2 answers

You can simply do:

 def getClosestSphere(ray: Ray, spheres: List[Sphere]): Sphere = { spheres.minBy(_ intersectRay ray) } 

Tip of style, aside:

When using a mutable collection, use qualified import. For java.util.SomeCollection first import java.{util => ju} , and then use the name ju.SomeCollection . For scala.collection.mutable.SomeCollection first import collection.mutable , and then use the name mutable.SomeCollection .

+14
source
 spheres.minBy(_.intersectRay(ray)) 
+5
source

Source: https://habr.com/ru/post/1391795/


All Articles