Scala 大括号(带或不带 return 语句)

发布于 2025-01-14 10:20:10 字数 1370 浏览 3 评论 0原文

我试图了解 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 CallOutput
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 CallOutput
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吲‖鸣 2025-01-21 10:20:10

花括号在此代码中无关紧要;它们都可以被省略而不会对结果产生任何影响。

return 而言,除非您知道它的作用(这不是您认为的作用),否则不要使用它。

函数的值是函数中最后一个表达式的值,因此您需要将 if 语句制作为单个 if/else 表达式:

def method(a: Int) = 
       if (a == 10) 10
       else if(a == 11) 11
       else if(a == 12) 12
       else if(a == 13) 13
       else 1
       

实际上,对于此类代码,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 single if/else expression:

def method(a: Int) = 
       if (a == 10) 10
       else if(a == 11) 11
       else if(a == 12) 12
       else if(a == 13) 13
       else 1
       

In practice a match is a better choice for this sort of code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文