scala-匹配序列和元组

  scala的模式匹配极其强大,其中有一种用法是用case语句匹配序列和元组。

 

  放码过来:

 

  

def parse(x: Any): String = x match {
    case List(0, _, _) => "three element list; 0 is the first one"
    case List(1, _*) => "unknow number of elements" 
case list: List[_] => "got a list $list"
case list @ List(1, _*) => "got a list : $list" case Array(_*) => "an array" case Vevtor(_*) => "a Vector" case (a,b,c) => s"three element tuple: $a, $b, $c" case (a,b,c,_) => "four elements tuple;" }

  其中,_表示一个元素,_*表示0个或多个元素

  List[_]这种写法可以匹配类型模式,而 @ List(1, _*)可以匹配一个变量绑定的模式

posted @ 2018-12-05 19:48  爱斯特拉冈  阅读(565)  评论(0编辑  收藏  举报