1 package chapter08
2
3 object Test03_MatchTupleExtend {
4 def main(args: Array[String]): Unit = {
5 // 1. 在变量声明时匹配
6 val (x, y) = (10, "hello")
7 println(s"x: $x, y: $y")
8
9 val List(first, second, _*) = List(23, 15, 9, 78)
10 println(s"first: $first, second: $second")
11
12 val fir :: sec :: rest = List(23, 15 , 9, 78)
13 println(s"first: $fir, second: $sec, rest: $rest")
14
15 println("=====================")
16
17 // 2. for推导式中进行模式匹配
18 val list: List[(String, Int)] = List(("a", 12), ("b", 35), ("c", 27), ("a", 13))
19
20 // 2.1 原本的遍历方式
21 for (elem <- list){
22 println(elem._1 + " " + elem._2)
23 }
24
25 // 2.2 将List的元素直接定义为元组,对变量赋值
26 for ((word, count) <- list ){
27 println(word + ": " + count)
28 }
29
30 println("-----------------------")
31 // 2.3 可以不考虑某个位置的变量,只遍历key或者value
32 for ((word, _) <- list)
33 println(word)
34
35 println("-----------------------")
36
37 // 2.4 可以指定某个位置的值必须是多少
38 for (("a", count) <- list){
39 println(count)
40 }
41 }
42