Scala模式匹配

 匹配字符串/类型/守卫

val arr = Array("a ", "b", "c")

val i = Random.nextInt(arr.length)

println(i)

val name = arr(i)

println(name)

name match {

case "a" => println("this is a...")

case "b" => {

println("this is b...")

}

case _ => println("other...")

}

println("-----------骚气的分割线-----------")

//定义一个数组

val arr:Array[Any] = Array("hello123", 1, 2.0, CaseDemo02, 2L)

//取出一个元素

val elem = arr(3)

elem match {

case x: Int => println("Int " + x)

case y: Double if(y >= 0) => println("Double "+ y) // if 守卫

 

case z: String => println("String " + z)

case w: Long => println("long " + w)

case CaseDemo02 => {

println("case demo 2")

//throw new Exception("not match exception")

}

case _ => { // 其他任意情况

println("no")

println("default")

}

}

 匹配数组

val arr = Array(1, 1, 7, 0, 2,3)

arr match {

case Array(0, 2, x, y) => println(x + " " + y)

case Array(2, 1, 7, y) => println("only 0 " + y)

case Array(1, 1, 7, _*) => println("0 ...") // _* 任意多个

case _ => println("something else")

}

 匹配集合

val lst = List(0, 3, 4)

println(lst.head)

println(lst.tail)

lst match {

  case 0 :: Nil => println("only 0")  //只有一个0元素的list

  case 7 :: 9 :: Nil => println("只有7和9的list")
  case x :: y :: Nil => println(s"x $x y $y")   //只有两个元素的list

  case m :: n if n.length>0 => println("只有头和尾的list") //if n.length>0  守卫
  case 0 :: a => println(s"value : $a")

  case _ => println("something else")

}

匹配元组

val tup = (1, 3, 7)

tup match {

case (3, x, y) => println(s"hello 123 $x , $y")

 

case (z, x, y) => println(s"$z, $x , $y")

case (_, w, 5) => println(w)

case _ => println("else")

}

 匹配样例类/样例对象

//样例类,模式匹配,封装数据(多例),不用 new 即可创建实例

case class SubmitTask(id: String, name: String)

case class HeartBeat(time: Long)

//样例对象,模式匹配(单例)

case object CheckTimeOutTask

val arr = Array(CheckTimeOutTask, new HeartBeat(123), HeartBeat(88888), new HeartBeat(666),

                            SubmitTask("0001", "task-0001"))

val i = Random.nextInt(arr.length)

val element = arr(i)

println(element)

element match {

case SubmitTask(id, name) => {

println(s"$id, $name")

}

case HeartBeat(time) => {

println(time)

}

case CheckTimeOutTask => {

println("check")

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值