Scala 入门笔记 - 模式匹配

    name match {
      case "aaa" => println("this is aaa")
      case "bbb" => println("this is bbb")
      case _ => println("lala")

    }


// 匹配类型
case str: String => ....
case int: Int => ....
case matchType: MatchType => .... // 匹配自定义类型

  // 自定义类型
  class MatchType {
  }

// 匹配数组、元组, 集合
val arr = Array(1, 2, 3, 6)

arr match {
case Array(3, a, b, c) => println(s"case: $a, $b, $c")
case Array(_, x, y, z) => println(s"case: $x, $y, $z")
case _ => println("no matched")
}

val tup = ("a", 1, 4)

tup match {
case ("c", b, 4) => println(s"case: $b")
case ("a", x, y) => println(s"case: $x, $y")
case _ => println("no matched")
}

val list1 = List(0, 1, 2, 3)

list1 match {
// Nil 是个空List, :: 从右向左运算 (0 :: Nil 生成一个List(0))
case 0 :: Nil => println("case1: 0")
case 2 :: a :: b :: c :: d :: Nil => println(s"case2: $a, $b, $c, $d")
case 0 :: a => println(s"case3: $a")
case List(0, a, b, c) => println(s"case4: $a, $b, $c")
case _ => println("hahaha")
}

// 匹配样例类
object CaseClassDemo {
def main(args: Array[String]): Unit = {
val arr = Array(CheckTimeOutTask, SubmitTask("1000", "task-0001"), HeartBeat(3000))

arr(Random.nextInt(arr.length)) match {
case CheckTimeOutTask => println("CheckTimeOutTime")
case SubmitTask(port, name) => println("SubmitTask")
case HeartBeat(time) => println("HeartBeet")
}
}
}

case class HeartBeat(time: Long)
case class SubmitTask(id: String, taskName: String)
case object CheckTimeOutTask










  

猜你喜欢

转载自www.cnblogs.com/sunnystone85/p/11363659.html
0条评论
添加一条新回复