scala unapply
case匹配规则:模式匹配
java中的switch
常量模式匹配
变量模式匹配
通配符模式匹配
package com.utils
object PatternDemo {
def main(args: Array[String]): Unit = {
//常量模式匹配
//常量字面值的匹配
val site="dwg.com"
site match {
case "dwg.com" =>println("success")
//相当于java中的default
//不需要break语句
case _ => println("fail")
}
//常量变量的匹配
val DWG="dwg.com"//不成功,是值匹配
site match {
// case DWG=>println("DWG")//DWG
case dwg=>println("success"+dwg)//变量匹配,如果是DWG则DWG变成dwg.com1,如果小写dwg则是变量匹配
case _=>println("fail")
}
//通配符模式的匹配
val list=List(1,2,3)
list match {
case List(_,_,3)=>println("success")
case _=>println("fail")
}
}
}
样例类匹配
类型匹配
package com.utils
import scala.util.Random
object PatternDemo2 {
// def main(args: Array[String]): Unit = {
//
// //做信息的甄别
// abstract class Notificaion
// //定义不同信息的样例类
// case class Email(sender:String,title:String,body:String) extends Notificaion
// case class SMS(caller:String,message:String) extends Notificaion
// case class VoiceRecording(contactName:String,link:String) extends Notificaion
//
// //做信息的识别
// def showNotification(notificaion: Notificaion):String={
// notificaion match {
// case Email(sender,title,body) if(sender=="张三") =>"you get a Email Message from "+sender
// case SMS(caller,message) => "you get a SMS Message from "+caller
// case VoiceRecording(contactName,link) => "you get a VoiceRecording Message from "+contactName
// case _ =>"you get a message not important"
// }
// }
//
// //创建一条信息
// val email=Email("张三","important","somemmmm")
// println(showNotification(email))
//
// }
//类型匹配
def main(args: Array[String]): Unit = {
val arr=Array("sss",1,2.3,'c')
//随机取数组中的一个元素
val obj=arr(Random.nextInt(4))
println(obj)
obj match {
case x:Int=>println(x)
case s:String=>println(s.toUpperCase())
case d:Double=>println(Integer.MAX_VALUE)
case _=>print("fail")
}
}
}