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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With