Question

Mindblock 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  
  }

Can you see what I'm doing? I have a List of Spheres, where each Sphere has a method intersectRay, returning a double.

I want to take the Sphere with the smallest result of that function. I KNOW there is a nice functional construct to let me do this in one line, I just can't see it :(

Was it helpful?

Solution

You could just do:

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

A style tip, as an aside:

When using a mutable collection, use qualified imports. 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.

OTHER TIPS

spheres.minBy(_.intersectRay(ray))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top