Scala's case Classes and Pattern Matching

Source: Internet
Author: User
Tags abstract constant constructor

This article will explain the ubiquitous case class and pattern matching in Scala, why put it together, because it is generally used in conjunction with pattern matching, and is used to never want to write Java code after this set of combinations, use Les s code to show more! Case Class

Case class refers to the word keyword in front of class, and here is an example:

Abstract class Animal case
class Dog (name:string) extends Animal case
class Cat (name:string) extends Animal

The case class has several different places than the normal class:

There is a factory method that uses this class name as the method name to instantiate the class, and the benefit is that you can create a new object directly by writing the class name without having to precede the new

Scala> val dog = Dog ("Zeus")
Dog:dog = Dog (Zeus)

The variable declarations in the class's argument list are prefixed with Val, so these arguments are the member variables of the class and can be called directly by the

scala> dog.name
res0:string = Zeus

The compiler automatically adds the toString, Hashcode, Equals method to the class

The compiler adds a copy method for copying and modifying your class

Scala> dog.copy (name = "Simba")
Res1:dog = Dog (Simba)

In fact, the biggest advantage is the ability to support pattern matching patterns matching pattern matching

The basic format is as follows, selector refers to the variable to be matched, the following corresponds to a number of possibilities, pattern is the specific category, such as a case class,expression, each pattern must be added case keyword, After the arrows face the corresponding expression

Selector match {case
  pattern1 = expression1 case
  pattern2 = expression2
  ...
}

Here is a simple example

def behavior (animal:animal) = Animal match {case
  Dog (name) = = println ("wangwangwang!")
  Case Cat (name) = println ("miaomiaomiao~") Case
  _ = =
}

Results:

scala> behavior (animal)
wangwangwang!

Note two: After match the expression is judged in the order in which it is written to determine the multiple options after the match, each time and only one will be selected, that is, you must ensure that all possibilities exist, even if you add a default option to do nothing, it will throw Matcherror exception Types of pattern matching

wildcard Match
Wildcard matching is the use of _ to match, will match to any object, the general wildcard match will be used for pattern matching default results, another use is when you do not care about the matching content, you can use a _ instead of a variable that needs to be named, the example is as follows:

Animal match {case
  Dog (_) = = println ("wangwangwang!")
  Case Cat (_) = println ("miaomiaomiao~") Case
  _ = =
}

constant Match
As the name implies, the type of match is a specific constant:

def describe (x:any) = x Match {case
  5 = ' Five ' case
  true = ' truth ' case
  ' hello ' = ' Hi '
  case Nil = "The Empty list" Case
  _ = "Something Else"
}

Variable Matching
Variable matches and wildcard matches can be matched to any object:

Expr match {case
  0 = "Zero" case
  SomethingElse = "Not zero:" + SomethingElse
}

But note that variables can only be used once, not case Dog (name, name).

In addition, adding an inverse quote to the variable will make the variable a constant match, for example:

Val pi = Math. Pi

expr Match {case
  ' pi ' = = ' pi = ' + pi case
  _ = ' OJBK '
}

Here's an extra look at the two uses of the anti-quote ' in Scala, one of which is to turn Scala's keywords into ordinary glyphs, such as Thread. ' Yield ' (), and the other is the lowercase identifier as a constant, as shown above.

Constructor Match
Constructor matching should be the most commonly used, that is, can match to a class and the corresponding member variables within the class, if the member variable is also a class, then you can continue to deep match

Animal match {case
  Dog (name) = println (name) Case
  _ = =
}

Sequence Matching
Can be used to match lists or collections

Expr Match {case
  List (0, _, _) = = println ("found it") case
  _ = =
}

The above example specifies that the number of lists is three, and if you want to specify a number, you can _* it in regular fashion.

Expr Match {case
  List (0, _*) = println ("found it") Case
  _ +
}

Multivariate group matching

Expr match{Case
  (A, b, c) = = println ("matched" + A + B + c) Case
  _ = +
}

type Match
Match to the specific type that belongs to

X Match {case
  s:string = s.length Case
  m:map[_, _] = = M.size Case
  _ + = 1
}

But notice here that the type match can only match to the type of the class, and cannot match the type of the argument to the class, for example, the following example:

def isintintmap (X:any) = x Match {case
  m:map[int, Int] ~ = True case
  _ = = False
}

The compiler will issue a warning:

<console>:12:warning:non-variable type argument Int in type pattern Scala.collection.immutable.map[int,int] (the Underlying of Map[int,int]) is unchecked since it's eliminated by Erasure case
         m:map[int, Int] = True
                 ^

This is because generics similar to Java,scala are implemented by type erasure, so the type parameter information at run time is unknown, so it corresponds to a pattern match, only to the type of the class, but not to the type of the parameter of the class.

The only exception is the array, where the element of the array exists in the array value, so it can be matched to its type

def isstringarray (X:any) = x Match {case
  a:array[string] = "Yes" case
  _ = "No"
}

Variable Binding
If we need some of the values in the pattern match and cannot be obtained directly, then we can use @ To bind the value to a variable, which can be used in subsequent expressions

Animal match {case
  Dog (name, b @ Behavior ("Run", _)) = = B Case
  _ = =
}
other points of attention

Pattern matching is not all selector match {alternatives}, but the following example is also a pattern match

For (country, city) <-capitals)
  println (' The capital of ' + Country + ' is ' + City)

In addition, if you need to add a judge to a pattern match, you can add the if condition after the match:

X Match {
  //Match only positive integers case
  n:int if 0 < n =
  ... Match only strings starting with letter ' A ' case
  s:string if s (0) = = ' a ' = = ' ...
}
Sealed Classes

Sometimes we can see the sealed keyword in front of a class as follows:

Sealed abstract class Animal case
class Dog (name:string) extends Animal case
class Cat (name:string) extends Anim Al

What are the characteristics of this class? In general, we will set a parent class to sealed whose subclasses must be under the same file. So what does this have to do with pattern matching? General pattern matching we will think of all the possibilities, the corresponding probability is usually a parent class of multiple subclasses, when we set the parent class to sealed, if you have a pattern match missing some subclasses, the compiler will give an alert, can prevent us from missing subclasses. Option

NullPointerException, who has experienced headaches in writing Java code, uses Option in Scala to solve this problem. The option class is used to refer to optional values, which may or may be empty, and when there is a value it results in the form of Some (x), and when there is no value, the result is none, which, in combination with pattern matching, gives the correct result:

Def show (x:option[string]) = x Match {case
  Some (s) = + S case
  None = "?"
}

We use map here to verify that because the Get method of map in Scala returns the Option object

Val Capitals = Map ("China"--"Beijing", "Japan", "Tykyo")

scala> Show (Capitals get "China")
Res19:str ing = Beijing

scala> Show (Capitals get "America")
res20:string =?
Summary

Pattern matching can replace two things in Java, one is an if statement and the other is a switch statement, so if you're still obsessed with any kind of if-judging logic, then get the pattern match into your code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.