Scala编译器不执行未返回的值

时间:2015-06-19 09:11:21

标签: scala functional-programming

我是scala的新手。最近我写了一些代码,发现scala有一些不寻常的行为。所以我写了这段代码

for {
  verification <- verifyReset(hash, timestamp, id)
  resp = if (verification) {
          setPassword(id, password)
          setActive(id)
          HttpResponse(Accepted, Seq(Location(Empty withPath Path / id)))
  } else HttpResponse(Unauthorized)
} yield resp

此处setPasswordsetActive用于执行某些数据库操作。但是在测试时我发现这个循环产生了resp(Accepted)而没有实际执行setpasswordsetActive。 为此,我假设由于编译器实际上不需要执行这些函数以返回最后一个语句,因此它没有执行它们。

然而,我写了一个类似的函数,它的行为与我的假设非常不同,

r = if(true){
     println("1st statement")
     println("2nd statement")
     2*3
}

我得到r为6(正常行为),但它也给了我控制台上的输出

1st statement 2nd statement

我不理解这一点,因为在计算2*3时我不需要执行println,那么为什么println已执行?

1 个答案:

答案 0 :(得分:4)

  

你的假设在这里是错误的。

它将在返回最后一个语句之前执行所有操作。因为默认情况下返回最后一个语句。

一定有其他错误

setPassword(id, password) setActive(id)