哪个Scala函数可以替换这个程序语句?

时间:2012-01-19 09:18:06

标签: scala functional-programming procedural

Mindblock在这里,但我无法弄清楚如何让它变得不那么难看:

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  
  }

你能看到我在做什么吗?我有一个球体列表,其中每个球体都有一个方法intersectRay,返回一个双。

我想要使用该函数最小结果的Sphere。我知道有一个很好的功能构造让我在一行中做到这一点,我只是看不到它:(

2 个答案:

答案 0 :(得分:14)

你可以这样做:

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

样式提示,作为旁白:

使用可变集合时,请使用合格的导入。对于java.util.SomeCollection,请先import java.{util => ju},然后使用名称ju.SomeCollection。对于scala.collection.mutable.SomeCollection,请先import collection.mutable,然后使用名称mutable.SomeCollection

答案 1 :(得分:5)

spheres.minBy(_.intersectRay(ray))