37
|
1 |
package CodeSamples
|
|
2 |
|
|
3 |
object PatternMatching {
|
|
4 |
def matchTest(x: Any): Any = x match {
|
|
5 |
case 1 => "one"
|
|
6 |
case "two" => 2
|
|
7 |
case y: Int => "scala.Int"
|
|
8 |
case _ => "many"
|
|
9 |
} //> matchTest: (x: Any)Any
|
|
10 |
|
|
11 |
matchTest("Two") //> res0: Any = many
|
|
12 |
matchTest("Test") //> res1: Any = many
|
|
13 |
matchTest(1) //> res2: Any = one
|
|
14 |
matchTest(2) //> res3: Any = scala.Int
|
|
15 |
|
|
16 |
def matchTest2(x: Any) {
|
|
17 |
x match {
|
|
18 |
case 1 => "one"
|
|
19 |
case "two" => 2
|
|
20 |
case y: Int => "scala.Int"
|
|
21 |
case _ => "many"
|
|
22 |
}
|
|
23 |
} //> matchTest2: (x: Any)Unit
|
|
24 |
|
|
25 |
//Matching Using case Classes
|
|
26 |
case class Person(name: String, age: Int)
|
|
27 |
|
|
28 |
def caseClassTest(): Unit = {
|
|
29 |
val alice = new Person("Alice", 25)
|
|
30 |
val bob = new Person("Bob", 32)
|
|
31 |
val charlie = new Person("Charlie", 32)
|
|
32 |
|
|
33 |
for (person <- List(alice, bob, charlie)) {
|
|
34 |
person match {
|
|
35 |
case Person("Alice", 25) => println("Hi Alice!")
|
|
36 |
case Person("Bob", 32) => println("Hi Bob!")
|
|
37 |
case Person(name, age) =>
|
|
38 |
println("Age: " + age + " year, name: " + name + "?")
|
|
39 |
}
|
|
40 |
}
|
|
41 |
} //> caseClassTest: ()Unit
|
|
42 |
|
|
43 |
caseClassTest() //> Hi Alice!
|
|
44 |
//| Hi Bob!
|
|
45 |
//| Age: 32 year, name: Charlie?
|
|
46 |
} |