scala入门初级代码训练-26array,list,tuple的模式匹配

原创文章,转载请注明出处!

原文地址: http://www.ptbird.cn/2016/07/19/scala-chuji-demo-26/

There I am,in the world more exciting!

by postbird

www.ptbird.cn



package com.ptbird.scala

/**
* Created by postbird on 2016/5/26.
*/
object MacthTest2 {
def main(args: Array[String]): Unit = {

def match_type(t: Any) = t match {
case p: Int => println("Int")
case p: String => println("String")
case m: Map[_, _] => println("Map")
case _ => println("Unknow Type")
}

match_type(2) //Int
match_type(Map("aa" -> 2, "bc" -> 2)) //Map
/** **********************数组 *********************************************/
def match_array(arr: Any) = arr match {
case Array(0) => println("Array " + "0")
case Array(x, y) => println("Array " + "x" + "y")
case Array(0, _*) => println("Array " + "0........")
case _ => println("Array " + " other")
}
match_array(Array(0, 2, 3, 4)) //Array 0........
match_array(Array(0)) //Array 0

/** **********************List ********************************************/

def match_list(list: Any) = list match {
case 0 :: Nil => println("List " + "0")
case x :: y :: Nil => println("List " + x + " " + y)
case 0 :: tail => println("List " + "0" + ".....")
case _ => println("list other..")
}
match_list(List(0))
match_list(List(0, 1))
match_list(List(0, 1, 2, 3, 4, 4))
// List 0
// List 0 1
// List 0.....
/** **********************tuple ********************************************/
def match_tuple(tuple:Any)=tuple match{
case (0,_)=>println("tuple "+"0")
case (x,0)=>println("tuple "+x)
case _ =>println("tuple other")
}
match_tuple((0,"scala"))
match_tuple((2,0))
match_tuple((0,1,2,3,3))
// tuple 0
// tuple 2
// tuple other

}
}

欢迎评论。
lingkb » scala入门初级代码训练-26array,list,tuple的模式匹配

发表评论