在 Scala 中简化具有多个出口点的嵌套 ifs?

Simplifying nested ifs with multiple exit points in Scala?

必须有更好的方法来做到这一点。我正在测试射线-三角形相交,我的代码看起来像这样

if(some condition) fail
else {
   ...
   if(some other condition) fail
   else {
      ...
      intersection
   }
}

有很多嵌套的 if。那真令人恶心。我这样做是为了不使用任何 return 语句。我可以在这里使用替代控制结构来管理各种方法退出点吗?

你可以用来理解:

val result: Option[BasicIntersection] = for {
  edge1 <- Some(vertices(1) - vertices(0))
  edge2 = vertices(2) - vertices(0)
  P = ray.v cross edge2
  determinant = edge1 dot P
  if !(determinant > -Utils.EPSILON && determinant < Utils.EPSILON)
  inv_determinant = 1.0/determinant
  T = ray.p - vertices(0)
  u = (T dot P) * inv_determinant
  if !(u < 0 || u > 1)
  Q = T cross edge1
  v = (ray.v dot Q) * inv_determinant
  if !(v < 0 || u + v > 1)
  t = (edge2 dot Q) * inv_determinant
  if !(t < Utils.EPSILON)
  hit = ray.p + ray.v*t
} yield
  if (hasUV) {
    val d0 = Math.abs((hit - vertices(0)).length)
    val d1 = Math.abs((hit - vertices(1)).length)
    val d2 = Math.abs((hit - vertices(2)).length)
    val uvAvg = (uv(0)*d0 + uv(1)*d1 + uv(2)*d2) / (d0 + d1 + d2)
    new BasicIntersection(hit, edge1 cross edge2, t, uvAvg)
  } else {
    new BasicIntersection(hit, edge1 cross edge2, t)
  }

result.getOrElse(new BasicIntersection()) // Your failure case