Java : 对一个值进行条件判断例如switch
模式匹配类似于Java
的switch case
。Scala
的模式匹配不仅可以匹配值还可以匹配类型、从上到下顺序匹配,如果匹配到则不再往下匹配、都匹配不上时,会匹配到case _
,相当于default
、match
的最外面的{ }
可以去掉看成一个语句。
def match_test(m:Any) = {
m match {
case 1 => println("num 1 ")
case m:Int => println("Int")
case _ => println("default")
}
}
package org.example
object MarchApp {
def main(args: Array[String]): Unit = {
def judeGrade(grade:String)={
grade match{
case "B" => println("Just so so")
case "A" => println("good")
case "S" => println("cool")
case _=> println("No.1")
}
}
judeGrade("S")
judeGrade("A")
judeGrade("SSS")
}
}
```scala
> cool
good
No.1
def greeting(array:Array[String]) = {
array match {
case Array("zs")=> println("hi,zs")
case Array(x,y)=> println(x+"and"+y)
case Array("zs",_*)=>println("zs and other")
case _=>println("everyone")
}
}
greeting(Array("zs"))
greeting(Array("zs","ls"))
hi,zs
zsandls
_*
: _
表示多个,*
是可变参数,
def greeting1(list:List[String]) = {
list match {
case "zs"::Nil=> println("hi,zs")
case x::y::Nil=> println(x+"and"+y)
case "zs"::tail =>println("zs and other")
case _=>println("everyone")
}
}
greeting1(List("zs"))
greeting1(List("zs","ls"))
}
hi,zs
zs and ls
def matchType(obj: Any) = {
obj match {
case x: Int => println("hi,int")
case y: String => println(y)
case m: Map[_, _] => println("map")
case _ => println("everyone")
}
}
matchType(Map(1 -> "yes"))
matchType(11)
matchType("hello")
}
try{
val i=10/0
println(i)
}catch {
case e:ArithmeticException=>println(e.getMessage)
case e:Exception=>println(e.getMessage)
}finally {
// 释放资源,一定会执行
}
/ by zero
cass class
可以直接使用,不用new
的
def caseclassMatch(person: Person) : Unit = {
person match {
case CTO(name, floor) => println("CTO name is: " + name + " )
case Employee(name , floor) => println( "Employee name is: " + name + ")
case_ =→>println("hello")
}
}
class Person
case class GT0(name:String,floor:String) extends Person
case class Employee(name:String, floor:String) extends Personcase class Other( name:String) extends Person
caseclassMatch(CTO("lisi","22"))
caseclassMatch(Employee( "zhangsan", "2"))caseclassMatch(0ther( "other" ))