package com.xing.listfile
/**
* Created by DengNi on 2017/2/11.
*/
class DataFramework
case class ComputationFramework(val name:String,val age:Int) extends DataFramework
case class StorageFramework(name:String ,age :Int) extends DataFramework
object helloPatternMatch {
def main(args: Array[String]) {
//模式匹配对值匹配
getSalary("spark")
getSalary("spark1")
getSalary("spark",12)
getSalary("spark1",16)
//模式匹配对数据类型的匹配
getMatchType(12)
getMatchType("Hi")
getMatchType(12.00)
getMatchType(Array(1,2))
getMatchType(Array("string"))
getMatchType(Seq(12))
//模式匹配对集合内容的匹配
getMatchCollection(Array("scala"))
getMatchCollection(Array("spark"))
getMatchCollection(Array("spark","scala"))
getMatchCollection(Array("java","spakdg")) //匹配到java后 后面的将不会在进行匹配
//模式匹配case class 匹配
getMatchCaseClass(ComputationFramework("hi", 12))
getMatchCaseClass(StorageFramework("hello",34))
///getMatchCaseClass(Array("string")) error can write another one that extends Data but not shows in the def function
//模式匹配对optional 匹配
getMatchOption("scala",Map("scala"-> "","spark"->"spark"))
getMatchOption("java",Map("scala"-> "","spark"->"spark"))
}
//模式匹配对值匹配
def getSalary(name:String): Unit ={
name match {
case "spark" => println("high");
case "hadoop" => println("low")
case _ => println("unknown")
}
}
def getSalary(name:String,age:Int): Unit ={
name match {
case "spark" => println("high "+ age);
case "hadoop" => println("low")
case _ if age > 15 => println("maybe " + age)
case _ if age <= 15 => println("unknown")
}
}
//模式匹配对数据类型的匹配
def getMatchType(msg:Any): Unit ={
msg match {
case i:Int => println("Integer")
case d:Double =>println("Double")
case s:String =>println("String")
case a:Array[String] =>println("Array[String]")
case a:Array[Int] =>println("Array[Int]")
case _ => println("unknown type")
}
}
//模式匹配对集合内容的匹配
def getMatchCollection(msg :Array[String]): Unit ={
msg match {
case Array("scala") => println("1 element")
case Array("spark","scala") => println("2 elements")
case Array("java",_*) => println("many elements")
case _ => println("unknown")
}
}
//模式匹配case class 匹配
def getMatchCaseClass(data:DataFramework): Unit ={ //传入的是父类的数据类型 ,这也解释了什么要extends
data match {
case ComputationFramework(name,age) => println("this is using to computation") //name and age passed by mian()
case StorageFramework(name,age) => println("this is for storage")
case _ => println("unknown")
}
}
//模式匹配对optional 匹配
def getMatchOption(name :String,contents:Map[String,String]): Unit ={ //采用的是Map Key 查 vale 的 情形
contents.get(name) match {
case Some(values) => println("exists")
case None => println("not exists")
}
}
}