Home > OS >  Scala Curly braces with and without return statement
Scala Curly braces with and without return statement

Time:03-16

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.

CodePudding user response:

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.

  • Related