1、模式匹配
Scala中提供了更加强大的模式匹配match case,Scala的match case与Java的switch case最大的不同点在于,Java的switch case仅能匹配变量的值;而Scala的match case可以匹配各种情况,比如变量的类型、集合的元素、有值或无值等。
变量 match {
case 值 => 代码
case 值 => 代码
case 值 => 代码
....
case _ => 代码
}
单个字符串匹配
def test1(grade:String): Unit ={
grade match {
case "A" => println("Excellent...")
case "B" => println("Good...")
case "C" => println("Just so so...")
case _ => println("You need to work harder...")
}
}
test1("A")
test1("E")
结果:
Excellent...
You need to work harder...
带有if条件的模式匹配
def test2(name:String,grade:String): Unit ={
grade match {
case "A" => println("Excellent...")
case "B" => println("Good....")
case "C" => println("Just so so....")
case _ if name == "haha" => println(name + ", you are a good boy, but ...")
case _ => println("You need to work harder....")
}
}
test2("zhangsan","B")
test2("haha","F")
test2("lisi","x")
结果:
Good....
haha, you are a good boy, but ...
You need to work harder....
数组的模式匹配
def test3(arr: Array[String]) {
arr match {
//只有一个hadoop元素
case Array("Hadoop") => println("Hi, Hadoop")
// 2个任意的元素
case Array(x, y) => println("Hi:" + x + " and " + y )
// zhangsan开头的任意多个元素
case Array("zhangsan", _*) => println("Hi, zhangsan and others")
case _ => println("hey, who are you?")
}
}
test3(Array("hadoop"))
test3(Array("haha","hehe"))
test3(Array("zhangsan","lisi","wangwu"))
结果:
hey, who are you?
Hi:haha and hehe
Hi, zhangsan and others
List模式匹配
def test4(list: List[String]): Unit = {
list match