Big data development Scala type checking and pattern matching


0. Preface

Type checking and type conversion are implemented in each language, such asJava IninstanceofandisInstance Of course, Scala also has, but compared with other languages,Scala In order to simplify the development, a powerful pattern matching is produced. Its principle and application are introducedJavaInswitch-caseIt is very similar, but its matching ability is stronger. It can not only match values and types, but also match classes and prefix classesSparkA lot of pattern matching is used in the source code, and the other is implicit conversion. In another article, this paper starts with type checking and type conversion, and introducesScalaSeveral common pattern matching and its use.

1. Type check

To test whether an object belongs to a given class, you can use theisInstanceOfmethod. If the test is successful, you can use theasInstanceOfMethod class
Type conversion.

//S to employee
val s = p.asInstanceOf[Employee]

Type conversion mainly has the following points to pay attention to:

  • If P points toEmployeeClass and its subclassesp.isInstanceOf[Employee]It will be successful.

  • If P is null, thenp.isInstanceOf[Employee]Will return false, andp.asInstanceOf[Employee]Null will be returned.

  • If P is not aEmployee, thenp.asInstanceOf[Employee]An exception is thrown.

  • If you want to test that P points to aEmployeeObject, but not its subclassif(p.getClass == classOf[Employee])
    classOfMethod defined inscala.PredefObject, so it is automatically introduced. However, pattern matching is usually a better choice than type checking and conversion.

p match{
//Treat s as employee
case s: Employee => ...
//P is not the case of employee
case _ => ....

2. Pattern matching

In summary, pattern matching in scala supports the following types of matching: value matching, type matching, set element matching, tuple matching, and matching with or without value. Let’s see how to use these types of matching from the perspective of code. First, the syntax structure of pattern matching is as follows:

Variable match{
  Case XX = > code

andJava There is no need to specifybreak, that is to saybreakThe effect of using a placeholder_To represent the default valuematch andifThere is also a return value.

2.1 value matching

Value matching, that is, similarJavaInteger, character or string matching in. However, there is something about guard matching (which can be understood as conditional matching by default)

//Character matching
def main(args: Array[String]): Unit = {
  val charStr = '6'
  charStr match {
    Case '+' = > println ("match with plus sign")
    Case '-' = > println ("match with minus sign")
    Case '*' = > println
    Case '/' = > println ("match with division sign")
    //Note: do not meet all the above conditions, execute the following code
    case _  =>Println ("no match, I'm the default")

//String matching
def main(args: Array[String]): Unit = {
  val arr = Array("hadoop", "zookeeper", "spark")
  val name = arr(Random.nextInt(arr.length))
  name match {
  Case "Hadoop" = > println ("big data distributed storage and computing framework...)
  Case "zookeeper" = > println ("big data distributed coordination service framework...)
  Case "spark" = > println ("big data distributed memory computing framework...)
  case _  =>Println ("I don't know you...)

//Guard matching
def main(args: Array[String]): Unit = {
  //Guard style
  val character = '*'
  val num = character match {
    case '+' => 1
    case '-' => 2
    case _ if character.equals('*') => 3
    case _ => 4
  println(character + " " + num)

2.2 type matching

Type matching is relative toJava In terms of advantages,JavaThe matching format is as follows:Case variable name: type, variable name can be_Instead

//Type matching
  def typeMathc (x: Any) = {
    x match {
      case _ : String = > println ("string")
      case _ : int = > println ("shaping")
      case _ : array [int] = > println ("positive star array")
      case _ => println("nothing")

2.3 matching array, tuple, set

Different from type matching, type matching can only match the whole large type, and this kind of matching can match similar to a certain class, but it can also limit some elements of the matching class

//Array pattern matching
  def arrayMatch(x: Array[Int]) = {
    x match {
      case Array(1,x,y) => println(x + ":" + y)
      case Array(1) => println("only 1 ....")
      case Array(1,_ *) = > println ("start with 1")
      case _ => println("nothing....")


  //List pattern matching
  def listMatch() = {
    val list = List(3, -1)
    //Pattern matching for a list is similar to array, but requires the list specific:: operator
    //The two basic units for constructing a list are nil and::, which are represented as an empty list
    //Tail returns a list of elements other than the first element
    //Separate matching: list with specified number of elements, list with specified elements, list starting with an element
    list match {
      case x :: y :: Nil => println(s"x: $x y: $y")
      case 0 :: Nil => println("only 0")
      case 1 :: _ => println("1 ...")
      case _ => println("something else")

  //Tuple matching
  def tupleMatch() = {
    val tuple = (5, 3, 7)
    tuple match {
      case (1, x, y) => println(s"1, $x, $y")
      case (_, z, 5) => println(z)
      case _ => println("else")

When there is no written value in the array, the following matching methods are equivalent, and any parameter is equal to complete type matching

case Array(_*) => println("*")
case _ : array [int] = > println ("whole array")

2.4 sample class matching

Case class is a special class in scala. When you declare the sample class, the following things happen automatically:

  • The parameters received by the main constructor usually do not need to be explicitly decorated with VaR or val. Scala will automatically use Val decoration

  • The associated object is automatically defined for the sample class, and the apply method is provided. The corresponding object can be constructed without the new keyword

  • The toString, equals, hashcode, and copy methods are generated, unless the display defines them

  • It inherits the two characteristics of product and serializable, that is to say, the sample class is serializable and can apply the method of product

Case class is multi instance, followed by construction parameters, and case object is single instance.

In addition, methods and fields can be added to the case class sample class, and can be used for pattern matching. How to understand the pattern matching of sample class? When using dynamic binding, we can judge whether an object belongs to a subclass object from the inheritance of sample class, and the parent class oriented interface can simplify the design of programming. As mentioned in the first partisInstanceOfAt the same time, the sample class can accept input parameters for corresponding subclass operations.

class Amount
//Define the sample class dollar and inherit the parent class of amount
case class Dollar(value: Double) extends Amount
//Define the sample class currency and inherit the parent class of amount
case class Currency(value: Double, unit: String) extends Amount
//Define the sample object nothing and inherit the parent class of amount
case object Nothing extends Amount
object CaseClassDemo {
  def main(args: Array[String]): Unit = {
  //User defined method, pattern matching to judge AMT type
  def judgeIdentity(amt: Amount): Unit = {
    amt match {
      case Dollar(value) => println(s"$value")
      case Currency(value, unit) => println(s"Oh noes,I got $unit")
      case _: Currency => println(s"Oh noes,I go")
      case Nothing => println("Oh,GOD!")

2.5 matching with or without values

Scala OptionOption types are used to indicate whether a value is optional, with or without a value.
Option[T]Is a container of optional values of type T, which can be accessed throughget()Function acquisitionOptionThe value of. If the value exists,Option[T] That’s one
Some. If it doesn’t exist,Option[T] It’s the objectNone
OptionIt is usually used in combination with pattern matching to determine whether a variable has a value or no valueMapReturn value ofOptionLet’s see the match.

val grades = Map("jacky" -> 90, "tom" -> 80, "jarry" -> 95)
  def getGrade(name: String): Unit = {
    val grade: Option[Int] = grades.get(name)
    grade match {
      Case some (grade) = > println ("grade): + grade)
      Case none = > println ("no score! ")
  def main(args: Array[String]): Unit = {
    Getgrade ("Zhang San")

3. Summary

ScalaPattern matching is used to simplify the code and achieve more powerful uncertain or deterministic matching. At the same time, it can also customize pattern matching, which is automatically used when matchingapply andunapplymethod.
Wu Xie, little third master, is a rookie in the field of big data and artificial intelligence.
Please pay more attention