Scala 模式匹配相当于java的switch,但是不需要break关键字。scala匹配到对应的值会立即退出,
模式匹配可用于替换java中的instance of
object PackageDemo extends App{
var x= 1
val result = x match{
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
// println(result) 结果 one
var result2 = x match{//另一种方式
case i if i==1 => "one"
case i if i==2 => "two"
case i if i==3 => "three"
case _ => "other"
}
// println(result2) 结果 one
def paramType(obj :Any) = obj match{
case 1 => 1 //匹配到int 1
case "one" => "one" //匹配到String 1
case x : Int =>"Int" //匹配到Int
case x : String =>"String" //匹配到String
case _ => "obj" //匹配所有
}
println(paramType(1))
println(paramType("one"))
println(paramType("StringParam"))
println(paramType(null))}
结果:
1
one
String
obj
case class
1.构造器默认是val,不建议用var
2.实例不用new因为apply
case class Book(name:String,author:String){//构造器默认是val,不建议用var
}
object Book{
val bookMatch = Book("呐喊","鲁迅")
bookMatch match{
case Book(name,author) => println("this is a book instance")
case _ => println("this is not a book instance")
}}
输出结果
this is a book instance