Tuesday 18 August 2020

Scala: Expression and statements

 Expression is a code snippet that returns a value, whereas the statement is a code snippet that does not return a value. 

Example 1:  initialization of value is a statement. Printing data to console using print or println method is a statement.

scala> var a = 10
var a: Int = 10

Example 2: 10 + 20 is an expression that performs the addition of integers 10 and 20 and returns the result.

scala> 10 + 20
val res25: Int = 30

Since 10 + 20 is an expression, you can chain function calls.

scala> (10 + 20).getClass
val res26: Class[Int] = int

scala> 

scala> (10 + 20).toLong.getClass
val res27: Class[Long] = long

Example 3: "hello" is an expression.

scala> "hello".toLowerCase()
val res31: String = hello

scala> "hello".toLowerCase().length()
val res32: Int = 5

for simplicity purposes, you can consider any right-side value is an expression.

 

For example, in the below snippet "Hello World" is an expression whereas complete snippet is a statement.

 

var data = "Hello World"

 

If the last line of the code snippet is an expression, then the result of evaluated expression is the return value of the snippet.

 

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 not 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

If the last line in a block is not an expression, then Scala returns an Unit (Unit has value ()).

scala> var x = {
     |   var a = 10
     |   var b = 10
     | }
var x: Unit = ()




Previous                                                    Next                                                    Home

No comments:

Post a Comment