Scala 大括号(带或不带 return 语句)
我试图了解 scala 花括号和带/不带 return 语句的基础知识。
def method(a:Int):Int = {
if(a == 10 ) 10
if(a == 11 ) {11}
if(a == 12 ) { return 12 }
if(a == 13 ) return {13}
1}
方法调用 | 输出 |
---|---|
method(10) | 1 |
method(11) | 1 |
method(12) | 12 |
method(13) | 13 |
从上面我们可以注意到,
- 方法调用的输出(12)&方法(13)符合预期。
- 而调用 method(10) & 的输出则为: method(11) 我们看到返回的值为 1 ,这很令人困惑,因为 scala return 关键字是不需要。
我注意到的另一件事是:
def method(a:Int) = {
if(a == 10 ) 10
if(a == 11 ) {11}
if(a == 12 ) {12}
if(a == 13 ) {13}
}
方法调用 | 输出 |
---|---|
method(10) | () |
method(11) | () |
method(12) | () |
method (13) | 13 |
上面的两个方法语句看起来很混乱。 请帮助澄清上述为什么返回值存在差异。
提前致谢。
I am trying to understand the basics of scala curly braces and with/without return statement.
def method(a:Int):Int = {
if(a == 10 ) 10
if(a == 11 ) {11}
if(a == 12 ) { return 12 }
if(a == 13 ) return {13}
1}
Method Call | Output |
---|---|
method(10) | 1 |
method(11) | 1 |
method(12) | 12 |
method(13) | 13 |
From the above we can note that
- the output of calls to method(12) & method(13) are as expected.
- Whereas the output of calls to method(10) & method(11) we see the value returned is 1 which is confusing given return keyword is not required for scala.
Another thing I noted was that :
def method(a:Int) = {
if(a == 10 ) 10
if(a == 11 ) {11}
if(a == 12 ) {12}
if(a == 13 ) {13}
}
Method Call | Output |
---|---|
method(10) | () |
method(11) | () |
method(12) | () |
method(13) | 13 |
The above two method statements seems confusing.
Kindly help to clarify the above why there is difference in values returned.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
花括号在此代码中无关紧要;它们都可以被省略而不会对结果产生任何影响。
就
return
而言,除非您知道它的作用(这不是您认为的作用),否则不要使用它。函数的值是函数中最后一个表达式的值,因此您需要将
if
语句制作为单个if
/else
表达式:实际上,对于此类代码,
match
是更好的选择。The curly braces are irrelevant in this code; they can all be omitted without any effect on the result.
As far as
return
goes, do not use it unless you know what it does (which isn't what you think it does).The value of a function is the value of the last expression in the function, so you need to make the
if
statements into a singleif
/else
expression:In practice a
match
is a better choice for this sort of code.