Home  >  Article  >  Java  >  A brief discussion on pattern matching in scala

A brief discussion on pattern matching in scala

不言
不言forward
2018-11-16 15:40:392112browse

The content of this article is about a brief discussion of scala pattern matching. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. scala pattern matching (pattern matching)

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

scala's pattern matching is similar to this,

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

where the variable e is followed by a match and a code block, where each case corresponds to a possible matching type. If it matches If successful, the code after => will be executed.

We can use a more 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 similar to switch in other languages, but it is actually very different. .

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

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

def parseArgument(arg: String) = arg match {
    //匹配值
    case "-h" | "--help" => displayHelp
    case "-v" | "--version" => displayVerion
    case whatever => unknownArgument(whatever)
}
def f(x: Any): String = x match {
    //匹配类型
    case i:Int => "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 return value of pattern matching is determined by the code block in the first matching pattern.

2. Why use pattern matching

You will find a problem when you see this. Isn’t pattern matching similar to if else? So why use pattern matching?

First of all, we need to understand that pattern matching essentially provides a convenient way of destructuring data structures. Taking scala as an example, pattern matching actually uses the function of the extractor in scala. The extractor actually It's the unapply () method in the class.

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

After understanding the essence of pattern matching, you will realize that in fact, if else is just a typical usage in pattern matching, but it is 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 also makes your code easier to test. For example, we can write the code for the match part above as follows:

  val user: User = new FreeUser("Daniel")
  //将返回结果存在一个常量中
  val message = user match {
    case FreeUser(name) => "it match here" + name
    case _ => "not me"
  }
  //可以随意使用该常量,实现解耦
  println(message)

This will give the code more flexibility and make further operations more convenient.

From the perspective of readability, using a lot of if else codes is undoubtedly more ugly, but if you use pattern matching, the code will be much simpler and clearer, and concise code will be more Easy to read.

The above is the detailed content of A brief discussion on pattern matching in scala. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete