scala 模式匹配
scala 模式匹配可以匹配多种,包括元组数组集合
package day01 import scala.util.Random object match1{ def main(args: Array[String]): Unit = { val arr = Array("a","b","c") val name = arr(Random.nextInt(arr.length)) // 匹配字符串 name match { case "a" => println("it is a!") case "b" => println("it is b!") // _ 表示全部匹配! case _ => println("it is nothing!") } // 匹配类型 val ar1 = Array("abc",100,12.34,true,match1) val el = ar1(Random.nextInt(ar1.length)) el match { case str:String => println(s"match String:$str") case int:Int => println(s"match int:$int") case bool: Boolean => println(s"match bool:$bool") case matchType:MatchType => println(s"match matchType:$matchType") case _:Any => println("not match") } // 匹配数组 val arr1 = Array(1,2,3,4) arr1 match { // a,b,c 表示占位符 case Array(1,a,b,c) => println(s"case: $a,$b,$c") case Array(_,x,y,z) => println(s"case: $x,$y $z") case _ =>println("Not match ") // 必须包含默认值! } } } class MatchType{ }