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.utilsimport 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")
}
}
}
?
?
?
?
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/hotMemo/p/9973918.html
總結
以上是生活随笔為你收集整理的scala unapply的全部內容,希望文章能夠幫你解決所遇到的問題。