如何在Scala中展平箭头代码

时间:2017-10-26 19:14:29

标签: scala

我知道恐怖代码是我们应该避免的反模式。 这个链接: https://blog.codinghorror.com/flattening-arrow-code/

提供了几种解决方法。但是,似乎它不适用于Scala。特别是当我想在方法开始时提早返回,如果不满足某些条件,因为"返回" Scala不鼓励使用关键字。

是否有一种优雅的方式允许我在Scala中执行以下操作?

def someFunction(): Try[MyDataType] = {
  if(some condition not met){
    // exit function
  }
  // do my actual work
}

1 个答案:

答案 0 :(得分:0)

如果您的代码结构具有可以封装在块中的合理大小的功能,那么我建议使用monadic流控制来实现所需的结果:

def funcA(x: Thing): Either[FailState, NextThing] = ...
def funcB(x: NextThing): Either[FailState, NextNextThing] = ...

for{
  next <- funcA(thing)
  nextNext <- funcB(next)
  ...
} yield finalCalculation(stuff)

这会使for-comprehension中的一个函数返回Left值时出现短路(因为Either现在正确偏向右侧。)