模式匹配在spark中非常重要,你可以在很多地方能看见模式匹配
def main(args: Array[String]): Unit = {
// trigger the constant patterns
println(echoWhatYouGaveMe(0))
println(echoWhatYouGaveMe(true))
println(echoWhatYouGaveMe("hello"))
println(echoWhatYouGaveMe(Nil))
println(echoWhatYouGaveMe(List(1,2,3)))
println(echoWhatYouGaveMe(List(1,2)))
println(echoWhatYouGaveMe(Vector(1,2,3,4)))
println(echoWhatYouGaveMe((1,2)))
println(echoWhatYouGaveMe((1,2,3)))
println(echoWhatYouGaveMe(Dogs("kkk")))
println("sum ="+sum(List(1,2,3,4,5)))
println("multiply ="+multiply(List(1,2,3,4,5)))
println(toInt("11"))
copyFile("D:\\spark.txt", "D:\\spark1.txt")
}
def echoWhatYouGaveMe(x :Any) = x match {
//常量匹配 constant patterns
case 0 => "zero"
case true => "true"
case "hello" => "you said 'hello'"
case Nil => "an empty List"
//序列匹配 sequence patterns
case List(1,a,b) => s"a three-element list with 0 as the first element second $a three $b"
case List(1,_*) => "a list beginning with 1, having any number of elements"
case Vector(1,_*)=> "a vector starting with 1, having any number of elements"
//元组 tuples
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"
//构造器 constructor patterns
case Person(first, "Alexander") => s"found an Alexander, first name = $first"
case Dogs("Suka") => "found a dog named Suka"
//typed patterns
case s: String => s"you gave me this string: $s"
case i: Int => s"thanks for the int: $i"
case f: Float => s"thanks for the float: $f"
case a: Array[Int] => s"an array of int: ${a.mkString(",")}"
case as:Array[String] => s"an array of strings: ${as.mkString(",")}"
case d: Dogs => s"dog: ${d.name}"
case list: List[_] => s"thanks for the List: $list"
case m: Map[_, _] => m.toString
//default
case _ => "Unknown"
}
//How to use Lists in Scala match expressions List最后一个元素是Nil,所以在case的时候一定要加Nil匹配
def sum(list:List[Int]):Int = list match{
case Nil => 0
case x :: rest => x + sum(rest)
}
def multiply(list:List[Int]):Int = list match{
case Nil => 1
case x :: rest => x * multiply(rest)
}
//模式匹配最显著的例子就是异常捕捉
def openAndReadAFile(filename:String) = {
try {
val lines = Source.fromFile(filename).getLines()
for(line <- lines){
println(line)
}
} catch {
case t: FileNotFoundException => t.printStackTrace()
case e: IOException => println("Had an IOException trying to read that file")
}
}