package cn.itcast.cases import scala.util.Random object CaseDemo01 extends App val arr = Array("hadoop", "zookeeper", "spark") val name = arr(Random.nextInt(arr.length)) name match case "hadoop" => println("大数据分布式存储和计算框架...") case "zookeeper" => println("大数据分布式协调服务框架...")
case "spark" => println("大数据分布式内存计算框架...") case _ => println("我不认识你...")
7.2. 匹配类型
package cn.itcast.cases import scala.util.Random object CaseDemo01 extends App val arr = Array("hello", 1, 2.0, CaseDemo) val v = arr(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")