문제

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

도움이 되었습니까?

해결책

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.

다른 팁

spheres.minBy(_.intersectRay(ray))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top