Type、Array、List、Tuple模式匹配实战解析之Scala学习笔记-18

package com.leegh.pattern_match

/**
* @author Guohui Li
*/
/**
* Type,Array模式匹配
*/
object Pattern_Match_More {
def main(args: Array[String]): Unit = {
def match_type(t: Any) = t match {
case p: Int => println("It is Integer")
case p: String => println("It is String")
case m: Map[_, _] => m.foreach(println)
case _ => println("Unknown type!!!")
}

match_type(2)
match_type(Map("Scala" -> "Spark"))

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("something else")
}
match_array(Array(0))
match_array(Array(0, 1))
match_array(Array(0, 1, 2, 3, 4, 5, 6))

def match_list(lst: Any) = lst match {
case 0 :: Nil => println("List:" + "0")
case x :: y :: Nil => println("List:" + x + " " + y)
case 0 :: tail => println("List:" + "0 ...")
case _ => println("something else")
}
match_list(List(0))
match_list(List(0, 1))
match_list(List(0, 1, 2, 3, 4, 5))

def match_tuple(tuple: Any) = tuple match {
case (0, _) => println("Tuple:" + "0")
case (x, _) => println("Tuple:" + x)
case _ => println("something else")
}
match_tuple((0, "Scala"))
match_tuple((2, 0))
match_tuple((0, 1, 2, 3, 4, 5))
}
}

 

附:

本博客说明:

1.整理思路,提高自己。

2.受教于王家林老师,​有所收获,故推荐。

3.博客注重实践,多余的文字就不多说了,都是做技术的。

4.信息来源于 DT大数据梦工厂微信公众账号:DT_Spark。​

DT大数据梦工厂的微信公众号是DT_Spark,每天都会有大数据实战视频发布,请您持续学习。

Scala 深入浅出实战经典(1-64讲)完整视频、PPT、代码下载:

百度云盘:http://pan.baidu.com/s/1c0noOt6
腾讯微云:http://url.cn/TnGbdC
360云盘:http://yunpan.cn/cQ4c2UALDjSKy 访问密码 45e2

posted on 2015-08-11 08:24  李格非  阅读(200)  评论(0编辑  收藏  举报