Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Scala function to replace this procedural statement?

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 :(

like image 505
Dominic Bou-Samra Avatar asked Dec 02 '22 00:12

Dominic Bou-Samra


1 Answers

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.

like image 179
missingfaktor Avatar answered Dec 05 '22 06:12

missingfaktor