第27讲:类型、数组、列表、元组模式匹配实战解析

  

除了普通的×××,字符串类型的模式匹配,scala还提供了很多形式的模式匹配。例如类型,数组,列表、元组


我们通过代码来说明。

类型模式匹配:判断传入值的类型

,,,,def  match_type (t :有),=,t  match  {   ,,,,,case  p :, Int =祝辞,println (“It  is  a 整数!”)   ,,,,,case  p :, String =祝辞,println (“It  is  a 字符串!,,content  is :”+ p)   ,,,,,case  m :,地图(_,_),=祝辞,m.foreach println ()   ,,,,,case  _ =祝辞,println (“Unknown 类型”)   ,,,}   ,,,,   ,,,match_type (1)   ,,,match_type(“火花”)   ,,,match_type (Map(“火花”→“scala 语言”))


运行结果如下

It  is  a 整数!   It  is  a 字符串!,,content  is :火花   (火花,scala 语言)

数组模式匹配:

,,,,def  match_array (arr :有),=,arr  match  {   ,,,,,case 数组(x),=祝辞,println(“数组(1):”,x),//,长度为1的数组,x代表数组中的值   ,,,,,case 数组(x, y),=祝辞,,println(“数组(2):”,x, y),//,长度为2的数组,x代表数组中的第一个值   ,,,,,case 数组(x) _ *),=祝辞,println(“任意一维数组:“(x),//任意长度数组,取第一个值   ,,,,,case 数组(_ *),=祝辞,println(“任意一维数组”),//任意长度数组   ,,,,}   ,,,,   ,,,match_array(数组(0))   ,,,match_array(数组(“火花”))   ,,,match_array(数组(“火花”,“scala”))   ,,,match_array(数组(“火花”,“scala”, 0, 4))


列表匹配:

,,,,def  match_list (lst :有),=,lst  match  {   ,,,,,case  0,::, Nil =祝辞,println(“列表:”+ 0),//零表示空列表   ,,,,,case 列表(x),=祝辞,println(“列表:“+ x)   ,,,,,case  x ::, y ::, Nil =祝辞,println(“列表:“+ x)   ,,,,,case  x ::, tail =祝辞,println(“列表:”+“多元素列表”),//尾表示列表的剩下所有元素   ,,,}   ,,,,   ,,,match_list(列表(0))   ,,,match_list(列表(“火花”))   ,,,match_list(列表(“火花”,“hadoop”))   ,,,match_list(列表(“火花”,1、2、4、5))


元组匹配

,,,,def  match_tuple (t :有),=,t  match  {   ,,,,,case (0, _),=祝辞,println(“二元元组,第一个值为0”)   ,,,,,case  (x, y),=祝辞,println(“二元元组,值为:" + x +”、“+ y)   ,,,,,case  _ =祝辞,println (“something 否则”)   ,,,}   ,,,,   ,,,match_tuple ((0, ' x '))   ,,,match_tuple ((' y ', ' x '))   ,,,match_tuple ((0, 1, 2, 3)



第27讲:类型、数组、列表、元组模式匹配实战解析