scala基础30-模式匹配进阶

object Test {
	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("Spark")
		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(1, 2))
		match_array(Array(0,1,2,3,4,5))
		
		//list匹配
		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, s) => println("Tuple: " + "0 " + s)
			case (x, 0) => println("Tuple: " + x)
			case _ => println("something else")
		}
		
		match_tuple((0, "scala"))
		match_tuple((2, 0))
		match_tuple((0, 1, 2, 3, 4, 5))
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值