|
scala match表达式
scala中的match表达式类似java中的switch语句,但功能比java中switch更强大。
java的switch case中只能用数字或常量,先来看看scala match的一个应用例子:
def greeting1(arg:String) {
arg match {
case "joe" => println("joe")
case a=>println("variable value is "+a)
case _ => println("not known")
}
}
def greeting2(arg:Array[String]) {
arg match {
case Array("joe") => println("hello joe")
case Array(a1,a2,a3) => println("hello "+a1 +","+a2+","+a3)
case Array("joe",_*) => println("hello joe and everyone")
case _ => println("hi")
}
}
greeting1("joe") //joe
greeting1("jack") //variable value is jack
greeting1("someone") //variable value is someone
greeting2(Array("joe")) //hello joe
greeting2(Array("zs","li","wu","zl")) //hi
greeting2(Array("joe","rose")) //hello joe and everyone
greeting2(Array("tom","jack")) //hi
greeting2(Array("mick","tom","marry")) //hello mick,tom,marry
|
|