defmain(args: Array[String]): Unit = { val charStr = '6' charStr match { case '+' => println("匹配上了加号") case '-' => println("匹配上了减号") case '*' => println("匹配上了乘号") case '/' => println("匹配上了除号") //注意:不满足以上所有情况,就执行下面的代码 case _ => println("都没有匹配上,我是默认值") } }
defmain(args: Array[String]): Unit = { 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("我不认识你...") } }
守卫式匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 所谓守卫就是添加if语句 objectMatchDemo{ defmain(args: Array[String]): Unit = { //守卫式 val character = '*' val num = character match { case '+' => 1 case '-' => 2 case _ if character.equals('*') => 3 case _ => 4 } println(character + " " + num) } }
val r1 = obj match { case x: Int => x case s: String => s.toInt // case BigInt => -1 //不能这么匹配 case _: BigInt => Int.MaxValue case m: Map[String, Int] => "Map[String, Int]类型的Map集合" case m: Map[_, _] => "Map集合" case a: Array[Int] => "It's an Array[Int]" case a: Array[String] => "It's an Array[String]" case a: Array[_] => "It's an array of something other than Int" case _ => 0 } println(r1 + ", " + r1.getClass.getName) }