Fahad/Eclipse/ScalaProjects/src/CodeSamples/PatternMatching.sc
author Chengsong
Mon, 09 May 2022 17:20:55 +0100
changeset 512 a4b86ced5c32
parent 36 d205c05e13d6
permissions -rw-r--r--
rewrite rules modified slightly

package CodeSamples

object PatternMatching {
  def matchTest(x: Any): Any = x match {
    case 1 => "one"
    case "two" => 2
    case y: Int => "scala.Int"
    case _ => "many"
  }                                               //> matchTest: (x: Any)Any

  matchTest("Two")                                //> res0: Any = many
  matchTest("Test")                               //> res1: Any = many
  matchTest(1)                                    //> res2: Any = one
  matchTest(2)                                    //> res3: Any = scala.Int

  def matchTest2(x: Any) {
    x match {
      case 1 => "one"
      case "two" => 2
      case y: Int => "scala.Int"
      case _ => "many"
    }
  }                                               //> matchTest2: (x: Any)Unit

  //Matching Using case Classes
  case class Person(name: String, age: Int)

  def caseClassTest(): Unit = {
    val alice = new Person("Alice", 25)
    val bob = new Person("Bob", 32)
    val charlie = new Person("Charlie", 32)

    for (person <- List(alice, bob, charlie)) {
      person match {
        case Person("Alice", 25) => println("Hi Alice!")
        case Person("Bob", 32) => println("Hi Bob!")
        case Person(name, age) =>
          println("Age: " + age + " year, name: " + name + "?")
      }
    }
  }                                               //> caseClassTest: ()Unit

  caseClassTest()                                 //> Hi Alice!
                                                  //| Hi Bob!
                                                  //| Age: 32 year, name: Charlie?
}