Tuesday, 18 August 2020

Scala: if/else expression blocks

 ‘if’ in Scala is modeled as an expression block.

Syntax

if(boolean expression){

         //expression block1

}

 

If the Boolean expression evaluates to true, expression block1 gets executed and the return value of ‘expression block1’ is the return value of the entire ‘if’ expression.
scala> var number = 2
var number: Int = 2

scala> var result = if (number % 2 == 0) {"Even Number"}
var result: Any = Even Number

scala> print(result)
Even Number

If the Boolean expression evaluates to false, then ‘Nothing’ will be returned. ‘Nothing’ is a special value in Scala to represent emptiness.

scala> var number = 3
var number: Int = 3

scala> var result = if (number % 2 == 0) {"Even Number"}
var result: Any = ()

scala> print(result)
()

As you see the output, type of variable result is ‘Any’. It is because Scala compiler smart enough to identify that this if block return a String value when evaluates to true and ‘Nothing’ when evaluates to false.

 

If-else expression block

If-else in Scala is modeled as an expression block.

 

Syntax

if(boolean expression){

         //expression block1

}else{

         //expression block2

}

 

If the Boolean expression evaluates to true, expression block1 gets executed and the return value of ‘expression block1’ is the return value of the entire if-else expression.

 

If the Boolean expression evaluates to false, expression block2 gets executed and the return value of ‘expression block2’ is the return value of the entire if-else expression.
scala> var number = 3
var number: Int = 3

scala> var result = if (number % 2 == 0) {"Even Number"} else {"Odd Number"}
var result: String = Odd Number

scala> 

scala> print(result)
Odd Number


Previous                                                    Next                                                    Home

No comments:

Post a Comment