Scala pattern matching

Pattern Matching

// Scala is no Java in the switch case grammar, corresponding, Scala provides a more powerful match case grammar, that pattern matching, like alternative switch case , match case also referred to as pattern matching

// Scala the match case with Java 's switch case that the biggest difference, Java 's switch case only matching value of the variable ratio of 1 , 2 , 3 and the like; and Scala the match case can match various situations, such as a variable type, the elements of the set with no value, or the value of

// match case syntax is as follows: Variable match {case value => Code } . If the value is underlined, it represents the default in all cases how to deal with the above is not satisfied. Further, match case , as long as a case branch satisfied and the process will not continue to the next is determined a case branch of. (With Java different, the Java 's switch case needed break stop)

// match case syntax for basic applications, is the value of a variable pattern matching

 

// Case: performance evaluation

def judgeGrade(grade: String) {

  grade match {

    case "A" => println("Excellent")

    case "B" => println("Good")

    case "C" => println("Just so so")

    case _ => println("you need work harder")

  }

}

 

 

 

Use in pattern matching if the guards

 

// Scala pattern matching syntax, there is a characteristic that can be case condition after the determination, not only a value, but may be combined with a later value if guard, double filtration

 

// Case: performance evaluation (upgrade version)

def judgeGrade(name: String, grade: String) {

  grade match {

    case "A" => println(name + ", you are excellent")

    case "B" => println(name + ", you are good")

    case "C" => println(name + ", you are just so so")

    case _ if name == "leo" => println(name + ", you are a good boy, come on")

    case _ => println("you need to work harder")

  }

}

 

 

 

Variable assignment in pattern matching

// Scala 's pattern matching syntax, there is a feature that, by default mode can be matched, underline, replaced by a variable name, then the value of the pattern matching syntax match will be assigned to this variable, which can in the back processing statements using the value to match

// Why has this syntax? ? think for a while. Because as long as the use of a case matched to the value, we know this is not just it! ! In this case the processing statement, is not directly write the program can use the known value!

// But for an underscore _ this case, does not meet all the previous case value, will enter _ such default be processed at this time if we need to get a specific value in dealing with statements for processing it? It would need to use this syntax variable assignment in pattern matching! !

 

// Case: performance evaluation (upgrade version)

def judgeGrade(name: String, grade: String) {

  grade match {

    case "A" => println(name + ", you are excellent")

    case "B" => println(name + ", you are good")

    case "C" => println(name + ", you are just so so")

    case _grade if name == "leo" => println(name + ", you are a good boy, come on, your grade is " + _grade)

    case _grade => println("you need to work harder, your grade is " + _grade)

  }

}

 

Pattern matching type

// Scala pattern matching a powerful place is that you can directly match type, not a value! ! ! This is java 's switch case absolutely impossible.

// theoretical knowledge: how to type match? Other syntax matching value is actually the same, but the match type, then, is to use " Case variables : type => Code" this syntax, rather than matching the value of the " Case value => Code" that syntax.

 

// Example: Exception Handling

import java.io._

 

def processException(e: Exception) {

  e match {

    case e1: IllegalArgumentException => println("you have illegal arguments! exception is: " + e1)

    case e2: FileNotFoundException => println("cannot find the file you need read or write!, exception is: " + e2)

    case e3: IOException => println("you got an error while you were doing IO operation! exception is: " + e3)

    case _: Exception => println("cannot know which exception you have!" )

  }

}

 IllegalArgumentException: Wrong parameter type

 

 

For Array and List for pattern matching

// for Array pattern matching, respectively, may be matched with the specified elements in the array, the array having the specified number of elements, starting with an element in the array

// to List pattern matching, the Array is similar, but requires the use of List specific :: operator

 

// Example: say hello to a friend

def greeting(arr: Array[String]) {

  arr match {

    case Array("Leo") => println("Hi, Leo!")

    case Array(girl1, girl2, girl3) => println("Hi, girls, nice to meet you. " + girl1 + " and " + girl2 + " and " + girl3)

    case Array("Leo", _*) => println("Hi, Leo, please introduce your friends to me.")

    case _ => println("hey, who are you?")

  }

}

 

 

 

def greeting(list: List[String]) {

  list match {

    case "Leo" :: Nil => println("Hi, Leo!")

    case girl1 :: girl2 :: girl3 :: Nil => println("Hi, girls, nice to meet you. " + girl1 + " and " + girl2 + " and " + girl3)

    case "Leo" :: tail => println("Hi, Leo, please introduce your friends to me.")

    case _ => println("hey, who are you?")

  }

}

 

 

 

case class matches the pattern

 

// Scala provides for a special class, a case class declared, Chinese sample may also be referred class. case class is actually somewhat similar to Java in the JavaBean concepts. That is only defined Field, , and by the Scala automatically provide compile-time getter and setter methods, but there is no Method, .

// Case class 's constructor accepts the main parameters usually do not need to use var or val modified, Scala automatically will use val modified (but if you use var modified, it will still follow var come)

// Scala automatically case class defines a companion object is Object , and defines the apply () method, which received the same main parameters of the constructor, and returns the case class objects

 

// Case: School Access

class Person

case class Teacher(name: String, subject: String) extends Person

case class Student(name: String, classroom: String) extends Person

 

def judgeIdentify(p: Person) {

  p match {

    case Teacher(name, subject) => println("Teacher, name is " + name + ", subject is " + subject)

    case Student(name, classroom) => println("Student, name is " + name + ", classroom is " + classroom)

    case _ => println("Illegal access, please go out of the school!")

  }  

}

 

 

 

 

 

 

 

 

Option and pattern matching

// Scala has a special type, called the Option . Option two values, one is s Some , it expressed values, one is None , showing no value.

// Option usually used for pattern matching, there is a variable used to determine the value or no value, than null to the more concise

// Option usage must master, because Spark source code makes extensive use of Option , such as s Some (A) , None of this grammar, it must be able to understand Option pattern matching, to be able to read the spark source.

 

// Case: the result inquiry

val grades = Map("Leo" -> "A", "Jack" -> "B", "Jen" -> "C")

 

def getGrade(name: String) {

  val grade = grades.get(name)

  grade match {

    case Some(grade) => println("your grade is " + grade)

    case None => println("Sorry, your grade information is not in the system")

  }

}

 

Guess you like

Origin www.cnblogs.com/YuanWeiBlogger/p/11442111.html