本文介绍了“返回"和“try-catch-finally"Scala 中的块评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个代码产生不同的结果:

The following two code generate different result:

def x = try{
  true
} finally false

invoke x 得到 true

invoke x gets true

def y:Boolean = try{
  return true
} finally {
  return false
}

调用 y 得到 false

return 版本的行为与 Java 相同.

the return version behave same as Java.

就我个人而言,我从不在 Scala 中使用return".但是很高兴知道 Scala 如何评估 try-catch-finally 块的值.谢谢.

Personally I never use 'return' in scala. But it's good to know how scala evaluate the value of a try-catch-finally block. Thanks.

推荐答案

不应该在finally块中有return语句(即使技术上允许,至少在Java中,例如C#禁止它).

You should not have a return statement in a finally block (even though it is technically allowed, at least in Java, C# for example forbids it).

如果 Scala 的 finally 块有一个隐式返回,那总是会破坏预期的返回值.所以这没有任何意义.

If the Scala finally block had an implicit return, that would always clobber the intended return value. So that makes no sense.

但我想如果你明确地那样写,它对你没有帮助.

But I suppose it cannot help you if you explicitly write it that way.

这篇关于“返回"和“try-catch-finally"Scala 中的块评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 18:38