Solution
- Normal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15val month = i match {
case 1 => "January"
case 2 => "February"
case 3 => "March"
case 4 => "April"
case 5 => "May"
case 6 => "June"
case 7 => "July"
case 8 => "August"
case 9 => "September"
case 10 => "October"
case 11 => "November"
case 12 => "December"
case _ => "Invalid month" // the default, catch-all
}
Discussion
- As demonstrated in other recipes, you aren’t limited to matching only integers; the match expression is incredibly flexible:
1
2
3
4
5
6
7
8def getClassAsString(x: Any):String = x match {
case s: String => s + " is a String"
case i: Int => "Int"
case f: Float => "Float"
case l: List[_] => "List"
case p: Person => "Person"
case _ => "Unknown"
}
Compare
- Use Compare Method
1
2
3
4
5
6
7def checkData(i:Int) ={
i compare 10 match {
case 1 => println("i > 10")
case 0 => println("i = 10")
case -1 => println("i < 10")
}
}