Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

5. Scala pattern matching

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

1. Case class

The Class modified with case is called Case Class. When the compiler sees the case-decorated class, it adds some additional features to the class:

1. The compiler adds a factory method with the name of the class to the Case Class, which is used to build the object of the class

Val v = Var ("x") / / you do not need to use the new keyword when building objects

2. By default, the compiler adds val to the value parameters of case class, so these value parameters are the same as the fields in a class.

V.name

3. The compiler automatically adds toString, hashCode and equals methods to case class. You can compare case class with = =, compare the types of case class and the value parameters in case class

Op.right = = Var ("x")

4. The compiler adds a copy method to case class so that the value parameter of case class can be modified. It is convenient to use copy if there are only a few specific value parameters in a case class that need to be changed.

Val opNew = op.copy (operator = "-")

Case can modify not only class, but also object, which represents a singleton object

The biggest advantage of case class is matching with pattern matching.

2. The difference between the match expression of Scala and java switch

1. Scala's match expression can calculate a value, but Java's switch can't.

2. The expression of pattern matching will never penetrate into the next case expression. If there is no break in the switch of java, it will penetrate to the next branch.

3. If no patterns are matched in pattern matching, a MatchError exception is thrown.

III. SealedClass

When you are using pattern matching, you definitely need to consider the case of all scenarios, sometimes we can use default instead of all the cases that have not been taken into account, but sometimes this default value is meaningless, how can you make sure that you can take all the situations into account? Let's ask the compiler to help us think about it. We can add a sealed keyword to the parent class of case class, and this sealed will help us do two things:

1: when we define pattern matching, if the whole scenario is not considered, the compiler will issue a warning

2: classes modified by sealed cannot be inherited by case class in other files

IV. Types of patterns

1. The wildcard pattern case _ can be used to match the default scene and in the case of the domain of an object that can be ignored

2. Constant mode

Def describe (x: Any) = x match {

Case 5 = > "five"

Case true = > "truth"

Case "hello" = > "hi!"

Case Nil = > "the empty list"

Case _ = > "something else"

}

Describe (5) / / res6: String = five

Describe (true) / / res7: String = truth

Describe ("hello") / / res8: String = hi!

Describe (Nil) / / res9: String = the empty list

Describe (List (1,2,3)) / / res10: String = something else

3. Variable mode

You can bind the value of the matched expression to a variable in the pattern, so that you can use this variable in expressions

Val I = 1 + 1

Var result = I match {

Case 0 = > "zero"

Case somethingElse = > "not zero:" + somethingElse

}

Println (result) / / not zero: 2

How does the compiler determine whether it is constant mode or variable mode?

Val pi = math.Pi

Result = E match {

Case pi = > "strange math? Pi =" + pi / / words that begin with lowercase letters are considered to be variable patterns by the compiler

}

Result = E match {

Case `pi` = > "strange math? Pi =" + pi / / constant mode with backquotation marks

Case _ = > "OK"

}

4. Constructor mode. Depth matching is supported

5. Sequence pattern. Fixed-length sequences or arrays are supported, as well as non-fixed-length.

V match {

Case List (0, _ *) = > println ("list it") / / matches a List with any element, and the first element equals 0

Case Array (0, _ *) = > println ("array it") / / matches an Array with any element, and the first element equals 0

Case _ = >

}

6. Tuple mode

Def tupleDemo (expr: Any) = expr match {

Case (a, b, c) = > println ("matched" + a + b + c)

Case _ = >

}

7. Type mode

Def generalSizeWithPattern (x: Any) = x match {

Case s: String = > s.length

Case m: Map [Int, Int] = > m.size

Case _ = >-1

}

With regard to type erasure, arrays are an exception, because arrays are treated specially in java and in scala, corresponding to different types of arrays in jvm, such as int [], float [], and so on.

IsIntIntMap (Map (1-> 1)) / / true

IsIntIntMap (Map ("abc"-> "abc")) / / true

IsStringArray (Array ("abc")) / / yes

IsStringArray (Array (1,2,3)) / / no

8. Variable binding

Val expr = UnOp ("abs", UnOp ("abs", Var ("x")

Expr match {

Case UnOp ("abs", e@UnOp ("abs", i@Var (_) = > println (e + "" + I)

Case _ = >

}

5. Mode guard

Conditions can be defined in the schema.

Def simplifyAdd (e: Expr) = e match {

Case BinOp ("+", a, b) if a = b = > BinOp ("*", b, Number (2))

Case _ = > e

}

VI. Pattern overlap

Try to avoid pattern overlap

Def simplifyBad (expr: Expr): Expr = expr match {

Case UnOp ("-", UnOp ("-", e)) = > e / / the first case

Case UnOp (op, e) = > UnOp (op, simplifyBad (e)) / / second case

}

When case1 belongs to a subset of case2, then case1 can be placed before case2, and if it is placed after case2, it will never be executed, and the compiler will warn unreachable code.

7. Option

An Option is treated as a container, with or without something. Some means there is only one thing. None means there is nothing.

Val opt = Some ("aaa")

Opt.getOrElse ("default")

Use in pattern matching:

Val capitals =

Map ("France"-> "Paris", "Japan"-> "Tokyo")

Def show (x: Option [String]) = x match {

Case Some (s) = > s

Case None = >?

}

Show (capitals get "Japan") / / res25: String = Tokyo

Show (capitals get "France") / / res26: String = Paris

Show (capitals get North Pole) / / res27: String =?

VIII. The use of patterns in variable definitions

Val myTuple = 123, "abc")

Val (number, string) = myTuple

Val exp = new BinOp ("*", Number (5), Number (1))

Val BinOp (op, left, right) = exp

Pattern is used in partial function

1. A case sequence as a full function (complete function)

Val withDefault: Option [Int] = > Int = {

Case Some (x) = > x

Case None = > 0

}

2. What happens if a case is missing? A warning will appear in the compilation

Val second: Option [Int] = > Int = {

Case Some (x) = > x

}

3. If our case list is a partial scenario, we need to tell the compiler that this is a partial function

Val partial: PartialFunction [Option [Int], Int] = {

Case Some (x) = > x

}

4. We use full functions as much as possible, because partial functions may throw exceptions if they don't take into account the case that needs to be handled.

The partial above has the same meaning as the p below.

Val p = new PartialFunction [Option [Int], Int] {

Override def isDefinedAt (x: Option [Int]) = x match {

Case Some (_) = > true

Case None = > false

}

Override def apply (v1: Option [Int]) = v1 match {

Case Some (x) = > x

}

5. If you want to use partial functions, the following mode is recommended

If (partial.isDefinedAt (None)) {

Partial (None) / / if run alone, an exception will still be thrown

}

Mode is used in for

Val results = List (Some ("apple"), None, Some ("orange"))

For (Some (fruit) "Paris", "Japan"-> "Tokyo")

For ((country, city)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report