Java: 对一个值进行条件判断,返回针对不同的条件进行不同的处理
Scala:
变量 match {
case value1 =>代码1,
case value2 =>代码2,
...
case _ => 代码N
}
object MatchApp extends App {
val names = Array("zhangsan","lisi","wangwu")
val name = names(Random.nextInt(names.length))
name match {
case "zhangsan" => println("张三...")
case "lisi" => println("李四...")
case _ => println("真的不知道你们在说什么")
}
}
def greeting(array:Array[String])={
array match{
case Array("zhangsan") => println("Hi zhangsan")
case Array(x,y) => println("Hi "+x+" , "+y)
case Array("zhangsan",_*) => println("Hi zhangsan and other friends")
case _ => println("Hi everybody")
}
}
image.png
def matchType(obj:Any)={
obj match {
case Int => println("Int")
case String => println("String")
case m:Map[_,_] => m.foreach(println)
case _ => println("other type")
}
}
image.png
class Person
case class CTO(name: String,floor:Int) extends Person
case class Employee(name: String,floor:Int) extends Person
case class Other(name:String) extends Person
def caseclassMatch(person: Person)={
person match{
case CTO(name,floor) => println("CTO name is "+name+", floor is "+floor)
case Employee(name,floor) => println("Employee name is "+name+", floor is "+floor)
case _ => println("other")
}
}