模式匹配

package com.zy.scala

import scala.util.Random

/**
* 模式匹配
*/
object CaseDemo {
def main(args: Array[String]): Unit = {
//匹配字符串
val arr1 = Array(" hadoop", " zookeeper", " spark ")
val name = arr1(Random.nextInt(arr1.length))
name match {
case " hadoop " => println(" 大数据分布式存储和计算框架 ...")
case " zookeeper " => println(" 大数据分布式协调服务框架 ...")
case " spark " => println(" 大数据分布式内存计算框架 ...")
case _ => println(" 我不认识你 ...")
} //匹配数据类型
val arr2 = Array("hello", 1, 2.0, CaseDemo)
val v = arr2(Random.nextInt(4))
println(v)
v match {
case x: Int => println("Int " + x)
case y: Double if (y >= 0) => println("Double " + y)
case z: String => println("String " + z)
case _ => throw new Exception("not match exception")
} //匹配数组
val arr = Array(1, 3, 5)
arr match {
case Array(1, x, y) => println(x + " " + y)
case Array(0) => println("only 0")
case Array(0, _*) => println("0 ...")
case _ => println("something else")
} //匹配集合
val lst = List(3, -1)
lst match {
case 0 :: Nil => println("only 0")
case x :: y :: Nil => println(s"x: $x y:$y")
case 0 :: tail => println("0 ...")
case _ => println("something else")
} //匹配元组
val tup = (1, 3, 7)
tup match {
case (1, x, y) => println(s"1, $x , $y")
case (_, z, 5) => println(z)
case _ => println("else")
} /**
* 注意:在 Scala 中列表要么为空(Nil 表示空列表)要么是一个 head 元素加上一个 tail 列表。
* 9 :: List(5, 2) :: 操作符是将给定的头和尾创建一个新的列表
* 注意::: 操作符是右结合的,如 9 :: 5 :: 2 :: Nil 相当于 9 :: (5 :: (2 :: Nil))
*/
}
}

样例类的模式匹配

package com.zy.scala

import scala.util.Random

//样例类
case class SubmitTask(id: String, name: String) case class HeartBeat(time: Long) case object CheckTimeOutTask object CaseClsDemo {
def main(args: Array[String]): Unit = { //模式匹配 样例类
val arr = Array(CheckTimeOutTask, HeartBeat(12333), SubmitTask("0001", "task- - 0001"))
arr(Random.nextInt(arr.length)) match {
case SubmitTask(id, name) => {
println(s" $id , $name")
}
case HeartBeat(time) => {
println(time)
}
case CheckTimeOutTask => {
println("check")
}
}
}
}
04-27 16:18