case class SendHeartBeat(id: String, time: Long)
case object CheckTimeOutWorker
// 匹配上第一个之后就不再匹配
object ScalaMatchCse {
def main(args: Array[String]): Unit = {
// 匹配字符串内容
def contentMatch(str: String) = str match {
case "aaa" => println("a")
case "aaa" => println("b")
case "aaa" => println("c")
case "aaa" => println("d")
case _ => println("没有") // _ 任意内容
}
contentMatch("aaa")
contentMatch("bbb")
contentMatch("ccc")
contentMatch("ddd")
// 匹配数据类型
def typeMatch(tp: Any) = tp match {
case x: Int => println(s"Int $x")
case y: Long => println(s"Long $y")
case b: Boolean => println(s"boolean $b")
case _ => println("没有")
}
typeMatch(1)
typeMatch(10L)
typeMatch(true)
typeMatch("Scala")
// 匹配Array
def arrayMatch(arr: Any) = arr match {
case Array(0) => println("只有一个0元素的数组")
case Array(0, _) => println("以0开头的,第二个元素可以是任意值的数组")
case Array(1, _, 3) => println("已1开头,3结尾,中间为任意元素的三个元素的数组")
case Array(1, _*) => println("已1开头,N个元素的数组") // _*标识0个或者多个任意类型的数据
}
arrayMatch(Array(0))
arrayMatch(Array(0, "1"))
arrayMatch(Array(1, true, 3))
arrayMatch(Array(8,9,10,100,666))
// 匹配List
println("----------匹配List--------")
def listMatch(list: Any) = list match {
case 0 :: Nil => println("只有一个0元素的List")
case 1 :: 2 :: Nil => println("只有1和2元素的List")
case x :: y :: z :: Nil => println("只有三个元素的List")
case m :: n if n.length > 0 => println("------") // 拥有head,和 tail的数组 if n.length > 0 守卫
case _ => println("匹配不上")
}
listMatch(List(0))
listMatch(List(1,2))
listMatch(List(3,4,446))
listMatch(List(123))
// 匹配元组
def tupleMatch(tuple: Any) = tuple match {
case (0, _) => println("元组的第一个元素为0, 第二个元素为任意类型的数据")
case (x, m, k) => println("拥有三个元素的元组")
case (_, "AK47") => println("AK47")
}
tupleMatch((0, 1))
tupleMatch(("1", 1, true))
tupleMatch((ScalaMatchCse, "ff12"))
// 匹配对象
def objMatch(obj: Any) = obj match {
case SendHeartBeat(x, y) => println(s"$x $y")
case CheckTimeOutWorker => println("CheckTimeOutWorker")
case "registerWorker" => println("registerWorker")
}
objMatch(SendHeartBeat("appid0000001", System.currentTimeMillis()))
objMatch(SendHeartBeat("xx", 100L))
objMatch(CheckTimeOutWorker)
objMatch("registerWorker")
}
}
Scala match
最新推荐文章于 2022-07-22 14:01:44 发布