Article From:

Scala pattern matching

pattern matching It can be said to be a very powerful language feature in scala. Of course, it is not unique to scala, but this does not prevent it from becoming a major tool in scala’s language.

scala The pattern matching is similar.

e match {
  case Pattern1 => do Something
  case Pattern2 if-clause => do others

The variable E is followed by a match and a block of code, where each case corresponds to a possible type of back-matching, and if the match is successful, it executes=> the following code.

We can use a specific example to see how pattern matching works:

case class Player(name: String, score: Int)
def printMessage(player: Player) = player match {
  case Player(_, score) if score > 100000 =>
    println("Get a job, dude!")
  case Player(name, _) =>
    println("Hey, $name, nice to see you again!")

It looks a bit like switch in other languages, but it’s quite different.

Take Java switch as an example, Java switch only does some basic type matching, then performs some actions, and there is no return value.

Scala’s pattern matching matching matching is much more powerful, in addition to matching values, it can also match types.

def parseArgument(arg: String) = arg match {
    //Matching valuecase "-h" | "--help" => displayHelp
    case "-v" | "--version" => displayVerion
    case whatever => unknownArgument(whatever)
def f(x: Any): String = x match {
    //Matching typeCase i: Int = gt;"integer: " + i
    case _:Double => "a double"
    case s:String => "I want to say " + s

At the same time, pattern matching has a return value, such as the match above, which returns a Unit. We can also modify the above code to return a string:

case class Player(name: String, score: Int)
def message(player: Player) = player match {
  case Player(_, score) if score > 100000 =>
    "Get a job, dude!"
  case Player(name, _) =>
    "Hey, $name, nice to see you again!"

It is worth mentioning that the pattern matching return value is determined by the block of code in the first matching pattern.

2. Why use pattern matching

Looking at this, you will find a question. Isn’t pattern matching similar to if else? So why use pattern matching?

First of all, we need to understand that pattern matching is essentially a convenient way to deconstruct data structures. Take Scala as an example, pattern matching actually uses the power of extractors in scala.Yes, the extractor is actually the unapply () method in the class.

trait User {
  def name: String
class FreeUser(val name: String) extends User
object FreeUser {
  //Extractordef unapply(user: FreeUser): Option[String] = Some(
  val user: User = new FreeUser("Daniel")
  user match {
    case FreeUser(name) => println("it match here" + name)
    case _ => println("not me")

Understanding the nature of pattern matching will lead you to the fact that if else is only a typical use of pattern matching, but not all of it.

At the same time, pattern matching allows you to decouple two things that don’t really belong to each other and makes your code easier to test. For example, the code in the match section above can be written as follows:

  val user: User = new FreeUser("Daniel")
  //Exist the returned result in a constantVal message = user match {case FreeUser(name) => "it match here" + name
    case _ => "not me"
  //The constant can be used freely to achieve decouplingPrintln (message)

This will give the code more flexibility, but also more convenient to do further operations.

From a readability point of view, using a lot of if else code is no doubt ugly, and if pattern matching is used, the code will be much simpler and clearer, while the simple code will be easier to read.


Original link
This article is the original content of Yunqi Community, which can not be reproduced without permission.

Leave a Reply

Your email address will not be published. Required fields are marked *