Scala Match and Case expressions like a switch statement

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-07 20:07:22 Viewed : 234


Scala Match and Case

Scala has a match expression,  like a Java switch statement.


Example:

Following example illustrates about Scala Match and Case

Save the file as − MatchExpressions.scala.

 

 MatchExpressions.scala

package runnerdev

object MatchExpressions extends App {

  //Example with int pattern  match

  val sc = new java.util.Scanner(System.in)

  println("Enter a value: ")

  val givenNumber = sc.nextInt();

  val result = givenNumber match {

    case 1 => println("one")

    case 2 => println("two")

    case _ => println("Invalid number") //Handling the default case

  }

  //Example with boolean  pattern match

  var boolVal = true;

  val booleanAsString = boolVal match {

    case true  => println("true")

    case false => println("false")

  }

  //Example with string pattern  match

  var dbName = "MongoDB"

  var dataBase = dbName match {

    case "SQL"        => println("Selected dataBase is :" + dbName)

    case "MongoDB"    => println("Selected dataBase is :" + dbName)

    case "Oracle 12c" => println("Selected dataBase is :" + dbName)

    case "SAP HANA"   => println("Selected dataBase is :" + dbName)

 

  }

}

compile and run the above example as follows 

scala> scalac MatchExpressions.scala

scala> scala MatchExpressions

OutPut:

Enter a value:

1

one

true

Selected dataBase is :MongoDB

Search
Sub-Categories
Related Articles

Leave a Comment: