在Scala模式匹配中,可以使用类型,通配符,序列,正则表达式,甚至可以深入获取对象的状态,这种对象状态的获取遵循一定的协议,也就是对象内部的状态的可见性由该类型的实现来控制,这使得我们能够轻易获取暴露的状态并应用于变量中。对象状态的获取往往被称为提取或解构。
一,简单的匹配
通过匹配boolean值来模拟掷硬币
def Macthing(): Unit ={
val bools=Seq(true,false)
for(bool<-bools){
bool match {
case true=>println("Got heads")
case false=>println("Got tails")
}
}
}
二,匹配特定的某个值,特定的某个类型
def Macthing2(): Unit ={
for{
x<- Seq(1,2,2.7,"one","tow",'four,"three")
}{
val str= x match {
case 1 =>"int 1"
case i:Int =>"other int:"+i
case d:Double=>"a double:"+x
case "one" =>"String one"
case s:String =>"other string:"+s
case unexpected=>"unexpectehd value:"+unexpected
}
println(str)
}
}
三,灵活匹配
def checkY(y:Int)={
for{
x<- Seq(99,100,101)
}{
val str=x match {
case 'y'=>"found y!"
case i:Int=>"int:"+i
}
println(str)
}
}
四,序列的匹配
val nonEmptySeq= Seq(1,2,3,4,5)
val emptySeq= Seq.empty[Int]
val nonEmptyList=List(1,2,3,4)
val emptyList= Nil
val nonEmptyVector=Vector(1,2,3)
val emptyVector= Vector.empty[Int]
val nonEmptyMap=Map("one"->1,"tow"->2)
val emptyMap=Map.empty[String,Int]
def seqToString[T](seq:Seq[T]):String=seq match {
case head+:tail =>s"$head+: "+seqToString(tail)
case Nil=>"Nil"
}
def testSeqToString(): Unit ={
for(seq<-Seq(
nonEmptySeq,emptySeq,nonEmptyList,emptyList,nonEmptyVector,emptyVector,
nonEmptyMap.toSeq,emptyMap.toSeq
)){
println(seqToString(seq))
}
}
五,元组的匹配
def testTuple(): Unit ={
val langs=Seq(
("Scala","Marticn","Odersky"),
("clojure","Rich","Hickey"),
("Lisp","John","McCarthy")
)
for(tuple<- langs){
tuple match{
case ("Scala",_,_)=>println("Found Scala")
case(lang,first,last)=>println(s"Found other languagse: $lang($first,$last)")
}
}
}
六,case中的守卫
def mathcTestGuard(): Unit ={
for(i<-Seq(1,2,3,4)){
i match {
case _ if i%2==0 => println(s"even: $i")
case _ => println(s"odd: $i")
}
}
}
七,case类的匹配
case class Address(streest:String,city:String,country:String)
case class Person(name:String,age :Int,address:Address)
val alice=Person("Alice",25,Address("1 Scala lane","Chicago","USA"))
val bob =Person("Bob",29,Address("2 java Ave","Miami","USA"))
val charlie =Person("Charlie",32,Address("3 python ct","Boston","USA"))
def caseclasstest()={
for(person <-Seq(alice,bob,charlie)){
person match {
case Person("Alice",25,Address(_,"Chcago",_))=>println("Hi Alice!")
case Person("Bob",29,Address("2 java Ave","Miami","USA"))=>println("hi Bob!")
case Person(name,age,_)=>println(s"Who are you,$age year-old persob named $name?")
}
}
}
八,模拟商场打印商品
def zipwithIndexTest(): Unit ={
val itemsCosts =Seq(("Pencil",0.52),("Paper",1.35),("Notebook",2.43))
val itemsCostsIndeices=itemsCosts.zipWithIndex
for(itemCostsIndex <- itemsCostsIndeices){
itemCostsIndex match{
case((name,cost),index)=>println(s"$index: $name costs $cost each")//返回的元组形式((name,cost),index)
}
}
}
九,从对象中取值
def getcaseTest(): Unit ={
for(person<-Seq(alice,bob,charlie)){
person match {
case p @ Person("Alice",25,address)=>println(s"Hi Alice")
case p @ Person("Bob",29,a @ Address(street,city,country))=>
println(s"Hi ${p.name}!age ${p.age},in ${a.city}")
case p @ Person(name,age,_)=>
println(s"who are you ,$age year-old person named $name? $p")
}
}
}