我是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
此处setPassword
和setActive
用于执行某些数据库操作。但是在测试时我发现这个循环产生了resp(Accepted
)而没有实际执行setpassword
和setActive
。
为此,我假设由于编译器实际上不需要执行这些函数以返回最后一个语句,因此它没有执行它们。
然而,我写了一个类似的函数,它的行为与我的假设非常不同,
r = if(true){
println("1st statement")
println("2nd statement")
2*3
}
我得到r
为6(正常行为),但它也给了我控制台上的输出
1st statement
2nd statement
我不理解这一点,因为在计算2*3
时我不需要执行println
,那么为什么println
已执行?
答案 0 :(得分:4)
你的假设在这里是错误的。
它将在返回最后一个语句之前执行所有操作。因为默认情况下返回最后一个语句。
一定有其他错误 setPassword(id, password)
setActive(id)