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?
}