1 package chapter08
2
3 object Test02_MatchTypes {
4 def main(args: Array[String]): Unit = {
5 // 1. 匹配常量
6 def describeConst(x: Any): String = x match {
7 case 1 => "Int one"
8 case "hello" => "String hello"
9 case true => "Boolean true"
10 case '+' => "Char +"
11 case _ => ""
12 }
13
14 println(describeConst("hello"))
15 println(describeConst('+'))
16 println(describeConst(0.3))
17
18 println("==================================")
19
20 // 2. 匹配类型
21 def describeType(x: Any): String = x match {
22 case i: Int => "Int " + i
23 case s: String => "String " + s
24 case list: List[String] => "List " + list
25 case array: Array[Int] => "Array[Int] " + array.mkString(",")
26 case a => "Something else: " + a
27 }
28
29 println(describeType(35))
30 println(describeType("hello"))
31 println(describeType(List("hi", "hello")))
32 println(describeType(List(2, 23)))
33 println(describeType(Array("hi", "hello")))
34 println(describeType(Array(2, 23)))
35
36 // 3. 匹配数组
37 for (arr <- List(
38 Array(0),
39 Array(1, 0),
40 Array(0, 1, 0),
41 Array(1, 1, 0),
42 Array(2, 3, 7, 15),
43 Array("hello", 1, 30),
44 )) {
45 val result = arr match {
46 case Array(0) => "0"
47 case Array(1, 0) => "Array(1, 0)"
48 case Array(x, y) => "Array: " + x + ", " + y // 匹配两元素数组
49 case Array(0, _*) => "以0开头的数组"
50 case Array(x, 1, z) => "中间为1的三元素数组"
51 case _ => "something else"
52 }
53
54 println(result)
55 }
56
57 println("=========================")
58
59 // 4. 匹配列表
60 // 方式一
61 for (list <- List(
62 List(0),
63 List(1, 0),
64 List(0, 0, 0),
65 List(1, 1, 0),
66 List(88),
67 List("hello")
68 )) {
69 val result = list match {
70 case List(0) => "0"
71 case List(x, y) => "List(x, y): " + x + ", " + y
72 case List(0, _*) => "List(0, ...)"
73 case List(a) => "List(a): " + a
74 case _ => "something else"
75 }
76 println(result)
77 }
78
79 // 方式二
80 val list1 = List(1, 2, 5, 7, 24)
81 val list = List(24)
82
83 list match {
84 case first :: second :: rest => println(s"first: $first, second: $second, rest: $rest")
85 case _ => println("something else")
86 }
87
88
89 println("===========================")
90 // 5. 匹配元组
91 for (tuple <- List(
92 (0, 1),
93 (0, 0),
94 (0, 1, 0),
95 (0, 1, 1),
96 (1, 23, 56),
97 ("hello", true, 0.5)
98 )){
99 val result = tuple match {
100 case (a, b) => "" + a + ", " + b
101 case (0, _) => "(0, _)"
102 case (a, 1, _) => "(a, 1, _) " + a
103 case (x, y, z) => "(x, y, z) " + x + " " + y + " " + z
104 case _ => "something else"
105 }
106 println(result)
107 }
108 }
109
作者:靠谱杨,
更多日常分享尽在我的VX公众号:小杨的挨踢IT生活