Friday 15 December 2017

Introduction to Scala - II

We continue with more Scala in this post. For all the work in this post, we will use Read-Evaluate-Print-Loop Scala interpreter. Some familiarity with Java will be of great help in understanding Scala. In this post, we will look at the control statements.

We begin with the if statements. First, we see the simple if statement:

scala> val x = 1
x: Int = 1

scala> if (x==1){
     |    println("x equals " + x)
     | }
x equals 1


The if is straightforward. It evaluates if x is equal to 1 and then println is executed. Next, we look at if else statements:

scala> val x = 5
x: Int = 5

scala> if (x>5){
     |    println(x + " is greater than 5")
     | }else{
     |    println(x + " is not greater than 5")
     | }
5 is not greater than 5


The if else statement prints the println in the after the else as only this flow is satisfied. The next is if else ... if else statement:

scala> val x = 10
x: Int = 10


scala> if (x>10){
     |    println(x + " is greater than 10")
     | } else if (x<10){
     |           println(x + " is less than 10")
     |        } else {
     |            println(x + " is equal to 10")
     |        }
10 is equal to 10


Next, we look at while loop. An example is shown below:

scala> var x = 10
x: Int = 10

scala> while (x<13){
     |   println("x is " + x)
     |   x=x+1
     | }
x is 10
x is 11
x is 12


The while loop can be rewritten as a do while loop as below:

scala> var x = 10
x: Int = 10

scala> do{
     | println("x is " + x)
     | x=x+1
     | } while (x<13)
x is 10
x is 11
x is 12


Lastly, we look at the for loop:

scala> for (x <- -2 to 2){
     |   println("x is " + x)
     | }
x is -2
x is -1
x is 0
x is 1
x is 2


We can add more statements in the for loop as shown below using a semi-colon to separate the statements. The for loop is then run with different combination of values of these variables.

scala> for (x <- 1 to 2 ; y <- 1 to 2){
     |   println("x*y is " + x*y)
     | }
x*y is 1
x*y is 2
x*y is 2
x*y is 4


Another variation of for is shown below:

scala> for (x <- -2 until 2 by 2){
     |   println("x is " + x)
     | }
x is -2
x is 0


In the above example, the end value is not considered and the for skips values by 2 as indicated.

Lastly, we take a look at the conventional switch case. Switch case is replicated in Scala by using the match keyword. The example is shown below:

scala> val x = 1
x: Int = 1

scala> x match {
     | case 1 => "One"
     | case 2 => "Two"
     | case _ => "Unknown"
     | }
res2: String = One


This type of match is generally used in pattern matching. The last case statement deals with the default case when no match can be made.  An example taking the default route is shown below:

scala> val x = 3
x: Int = 3

scala> x match {
     | case 1 => "One"
     | case 2 => "Two"
     | case _ => "Unknown"
     | }
res3: String = Unknown


This concludes the different control structures in Scala.