Tuesday 18 August 2020

Scala: Expression Blocks

 If the last line of a block is an expression, it is called expression block.

Example

var interest1 = {var rateOfInterest = 2; var time = 15; (principle * rateOfInterest * time) / 100}

 

In the above snippet, last line of the code block is an expression, so the expression value is assigned to the variable ‘interest1’. You need to explicitly return the value if the last line of the code snippet is an expression.
scala> var principle = 10000
var principle: Int = 10000

scala> var interest1 = {var rateOfInterest = 2; var time = 15; (principle * rateOfInterest * time) / 100}
var interest1: Int = 3000

Many conditional and loops constructs in Java are modeled as expressions in Scala. For example, if, if-else, for loop, is modeled as expressions.

 

For example, you can assign the return value of the if-else expression to a variable.

 

var welcomeMsg = if (gender == "Male") {"Hello Mr." + name + " " + msg} else {"Hello Madam " + name + " " + msg}
scala> var msg = "Good Morning"
var msg: String = Good Morning

scala> var name = "Krishna"
var name: String = Krishna

scala> var gender = "Male"
var gender: String = Male

scala> var welcomeMsg = if (gender == "Male") {"Hello Mr." + name + " " + msg} else {"Hello Madam " + name + " " + msg}
var welcomeMsg: String = Hello Mr.Krishna Good Morning


Previous                                                    Next                                                    Home

No comments:

Post a Comment