我知道恐怖代码是我们应该避免的反模式。 这个链接: 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
}
答案 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
现在正确偏向右侧。)