Scala - Conditional Expressions and Pattern Matching

Scala Conditional Expressions

If statement
if(condition){  
    // Statements to be executed when the condition is true
}  
If-else statement
if(condition){  
    // If block statements to be executed when the condition is true
} else {  
    // Else block statements to be executed when the condition is false
}
Nested if-else statement
if(condition){  
    // If block statements to be executed when the condition is true
    if(conditionX){  
       // If block statements to be executed when the conditionX is true
   } else {  
       // Else bock statements to be executed when the conditionX is false
   }  
} else {  
    // Else block statements to be executed  
}  
If-else-if ladder statement
if (conditionX){    
   //Statements to be executed when conditionX is true
} else if (conditionY){    
   //Statements to be executed when conditionY is true
...
else {    
   //Statements to be executed when all the conditions are false
} 
Alternative of Ternary Operators as Scala If Statement 
- Scala does not have ternary operator concept like C/C++.
- It provides more powerful "if statement" which can return value and whose return value can be assigned to a function.
object HelloObject {
  def main(args : Array[String]){
    var status=Numcheck(-20)
    println(status)
  }
  def Numcheck(a:Int)= if(a>=0) "Positive" else "Negative"
}
OUTPUT :: Negative

++++++++++++++++++++++++++

Scala Pattern Matching

-Pattern matching is same as switch case. 
-It matches the best case available in the pattern. [Example-1]
-Match expression can also return case value and the returned case value can also be assigned to a function. [Example-2]
 -We can define method having a match with cases for any type of data. [Example-3]
object HelloObject1 {
  def main(args: Array[String]): Unit = {
    //Scala Pattern Matching Example-1    
    var grade = 'A'    
    grade match {
      case 'O' => println("Outstanding")
      case 'E' => println("Excellent")
      case 'A' => println("Good")
      case 'B' => println("Average")
      case _ => println("Fail")
    }
  }
}
OUTPUT : Good
+++++++++++++
object HelloObject2 {
  def main(args : Array[String]): Unit = {
    //Scala Pattern Matching Example-2
    println(myGrade('E'))
  }
  def myGrade(grade : Char) : String = grade match{
    case 'O' => "Outstanding"
    case 'E' => "Excellent"    case 'A' => "Good"
    case 'B' => "Average"    case _   => "Fail"  }
}
OUTPUT : Excellent
+++++++++++++
-Any is a class in scala which is a super class of all data types and deals with all type of data. 
-Let's see an example.
------------
Example-2::  
object HelloObject6 {

  def main(args : Array[String]): Unit = {
    var result = search("Hello")
    println(result)

  }
    def search(x:Any):Any= x match{
      case 1 => "One"
      case 2 => "Two"
      case "Hello" => "Hello world"
      case _ => "Other"
    }
}

Post a Comment

0 Comments