除了更加“Java友好”外,Scala提供return
语句的真正原因是什么?
for(i<- 1 to bezillion; j <- i to bezillion+6){
if(expensiveCalculation(i, j)){
return otherExpensiveCalculation(i, j)
}
withExpensiveResource(urlForExpensiveResource){ resource =>
// do a bunch of stuff
if(done) return
//do a bunch of other stuff
if(reallyDoneThisTime) return
//final batch of stuff
}
这提供的是为了适应那些难以或繁琐地安排所有控制流路径汇聚到方法的词法结尾的情况。
尽管像Dave Griffith所说的可以消除对return
的任何使用,但通常这样做比仅仅用明显的return
来中断执行更加混乱难懂。
还要注意,return
返回的是方法,而不是可能在方法中定义的函数(文字)。
以下是一个例子
这个方法有很多if-else语句来控制流程,因为没有返回(这就是我想到的,你可以用你的想象力来扩展它)。我从一个实际的例子中提取出来并修改成了一个虚拟代码(实际上比这个还要长):
没有返回值:
def process(request: Request[RawBuffer]): Result = {
if (condition1) {
error()
} else {
val condition2 = doSomethingElse()
if (!condition2) {
error()
} else {
val reply = doAnotherThing()
if (reply == null) {
Logger.warn("Receipt is null. Send bad request")
BadRequest("Coudln't receive receipt")
} else {
reply.hede = initializeHede()
if (reply.hede.isGood) {
success()
} else {
error()
}
}
}
}
}
带返回值的函数:
def process(request: Request[RawBuffer]): Result = {
if (condition1) {
return error()
}
val condition2 = doSomethingElse()
if (!condition2) {
return error()
}
val reply = doAnotherThing()
if (reply == null) {
Logger.warn("Receipt is null. Send bad request")
return BadRequest("Coudln't receive receipt")
}
reply.hede = initializeHede()
if (reply.hede.isGood)
return success()
return error()
}
在编写命令式风格的代码时,我认为return
是一个有用的东西,这通常意味着I/O代码。如果你正在编写纯函数式代码,你不需要(也不应该使用)return
。但是对于函数式代码,你可能需要惰性来获得等效于可以使用return
“提前退出”的命令式代码的性能。