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

The good programmer big data tutorials share the pattern matching and sample classes of the Scala series

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

The good programmer big data tutorials share the pattern matching and sample classes of the Scala series

1. Sample class

In Scala, sample class is a special class, and sample class is immutable.

It can be compared by value and can be used for pattern matching.

Define a sample class:

1. Every parameter in the constructor is val unless it is explicitly declared as var

two。 Accompanying objects provide apply, which allows you to construct corresponding objects without using the new keyword

Case class Point (x: Int, y: Int)

Create a sample class object:

Val point = Point (1,2)

Val anotherPoint = Point (1,2)

Val yetAnotherPoint = Point (2,2)

/ / access object value

Point.x

Point.x = 1 / / No

Compare the sample class objects by values:

If (point = = anotherPoint) {

Println (point + "and" + anotherPoint + "are the same.")

} else {

Println (point + "and" + anotherPoint + "are different.")

}

/ / Point (1Pol 2) is the same as Point (1Jue 2).

If (point = = yetAnotherPoint) {

Println (point + "and" + yetAnotherPoint + "are the same.")

} else {

Println (point + "and" + yetAnotherPoint + "are different.")

}

/ / Point (1jue 2) and Point (2jue 2) are different.

Copy of the sample class

You can create a (shallow) copy of an instance of a case class simply by using the copy method. You can optionally change the constructor arguments.

Case class Message (sender: String, recipient: String, body: String)

Val message4 = Message ("julien@bretagne.fr", "travis@washington.us", "Me zo o komz gant ma amezeg")

Val message5 = message4.copy (sender = message4.recipient, recipient = "claire@bourgogne.fr")

Message5.sender / / travis@washington.us

Message5.recipient / / claire@bourgogne.fr

Message5.body / / "Me zo o komz gant ma amezeg"

Use the sample class in pattern matching:

Abstract class Amount

/ / inherits two sample classes of ordinary classes

Case class Dollar (value: Double) extends Amount

Case class Currency (value: Double, unit: String) extends Amount

Case object Nothing extends Amount

Object CaseClassDemo {

Def main (args: Array [String]): Unit = {

Val amt = new Dollar (10)

PatternMatch (amt)

}

Def patternMatch (amt: Amount) {

Amt match {

Case Dollar (v) = > println ("$" + v)

Case Currency (_, u) = > println ("Oh noes, I got" + u)

Case Nothing = > println ("nothing") / / sample object does not have ()

}

}

}

Declare the sample class, and the following things happen automatically:

1. Provides a unapply method to make pattern matching work

two。 Generate toString equals hashCode copy methods unless the definition of those methods is shown.

two。 Pattern matching

1. Better switch

Java-like switch code in Scala:

Note:

Scala's pattern matching matches only one branch, and you don't need to use a breakstatement, because it doesn't fall into the next branch. Match is an expression, and like an if expression, it has a value:

Object PatternDemo {

Def main (args: Array [String]): Unit = {

Var sign = 0

Val ch: Char ='p'

Val valchar ='p'

Var digit = 0

/ / match is an expression

Ch match {

Case'+'= > sign = 1

Case'-'= > sign =-1

/ / use | split multiple options

Case'*'|'x' = > sign = 2

/ / variables can be used

/ / if the case keyword is followed by a variable name, the matching expression is assigned to that variable.

Case valchar = > sign = 3

/ / case is similar to default in Java

/ / if no pattern can match, a MacthError will be thrown

/ / you can add guards to the mode

Case if Character.isDigit (ch) = > digit = Character.digit (ch, 10)

}

Println ("sign =" + sign)

}

}

1 constant mode (constant patterns) contains constant variables and constant literals

Scala > val site = "alibaba.com"

Scala > site match {case "alibaba.com" = > println ("ok")}

Scala > val ALIBABA= "alibaba.com"

/ / Note that constants must start with uppercase letters.

Scala > def foo (s:String) {s match {case ALIBABA = > println ("ok")}}

There is no difference between constant mode and ordinary if to compare whether two objects are equal (equals), and it doesn't feel any power.

2 variable mode (variable patterns)

To be exact, there is no matching judgment process for the simple variable pattern, but the incoming object is given a new variable name.

Scala > site match {case whateverName = > println (whateverName)}

The above replaces the site object to match with the whateverName variable name, so it will always match. However, there is a convention that for a variable, it must start with a lowercase letter, otherwise it will be treated as a constant variable. For example, if the whateverName above is written as WhateverName, it will look for the variable of the WhateverName. If it is found, it will be more equal, and if it cannot be found, it will make an error.

Variable patterns are not usually used alone, but in a combination of multiple patterns, such as

List (1) match {case List (x)) = > println (x)}

The x in it is marked with the variable x for the first element that matches.

3 wildcard mode (wildcard patterns)

The wildcard is underlined, which can be understood as a special variable or placeholder. A simple wildcard pattern usually occurs on the last line of a pattern match, and case = > it can match any object and is used to handle all other unsuccessful matches. Wildcard patterns are also often used in combination with other patterns:

Scala > List (1 ok 2) match {case List (, 3) = > println ("ok")}

The above List (, 3) uses two wildcards to represent the first and second elements, which can be any type of wildcard that is usually used to represent parts that don't care, unlike variable patterns that can be used in subsequent logic.

4. Sample class matching

/ / define a sample class

Abstract class Notification

Case class Email (sender: String, title: String, body: String) extends Notification

Case class SMS (caller: String, message: String) extends Notification

Case class VoiceRecording (contactName: String, link: String) extends Notification

/ / pattern matching based on sample classes

Def showNotification (notification: Notification): String = {

Notification match {

Case Email (email, title,) = >

S "You got an email from $email with title: $title"

Case SMS (number, message) = >

S "You got an SMS from $number! Message: $message"

Case VoiceRecording (name, link) = >

S "you received a Voice Recording from $name! Click the link to hear it: $link"

}

}

Val someSms = SMS ("12345", "Are you there?")

Val someVoiceRecording = VoiceRecording ("Tom", "voicerecording.org/id/123")

Println (showNotification (someSms)) / / result: You got an SMS from 12345! Message: Are you there?

Println (showNotification (someVoiceRecording)) / / result: you received a VoiceRecording from Tom! Click the link to hear it: voicerecording.org/id/123

two。 Mode with guards

Add Boolean expressions or conditional expressions to make the match more specific.

Def showImportantNotification (notification: Notification, importantPeopleInfo: Seq [String]): String = {

Notification match {

/ / only match the contents of email in the importantPeople list

Case Email (email,) if importantPeopleInfo.contains (email) = >

"You got an email from special someone!"

Case SMS (number,) if importantPeopleInfo.contains (number) = >

"You got an SMS from special someone!"

Case other = >

ShowNotification (other) / / nothing special, delegate to our original showNotification function

}

}

Val importantPeopleInfo = Seq ("867-5309", "jenny@gmail.com")

Val someSms = SMS ("867-5309", "Are you there?")

Val someVoiceRecording = VoiceRecording ("Tom", "voicerecording.org/id/123")

Val importantEmail = Email ("jenny@gmail.com", "Drinks tonight?", "I'm free after 5!")

Val importantSms = SMS ("867-5309", "Ihumm here! Where are you?")

Println (showImportantNotification (someSms, importantPeopleInfo))

Println (showImportantNotification (someVoiceRecording, importantPeopleInfo))

Println (showImportantNotification (importantEmail, importantPeopleInfo))

Println (showImportantNotification (importantSms, importantPeopleInfo))

5. Type matching

You can match expression types:

Val arr = Array ("hs", 1,2.0,'a')

Val obj = arr (Random.nextInt (4))

Println (obj)

Obj match {

Case x: Int = > println (x)

Case s: String = > println (s.toUpperCase)

Case: Double = > println (Int.MaxValue)

Case = > 0

}

Note: when you match a type, you must give a variable name, otherwise you will match the object itself:

Obj match {

Case: BigInt = > Int.MaxValue / / matches any object of type BigInt

Case BigInt = >-1 / / matches BigInt objects of type Class

}

Matching occurs at run time, and the type information of generics in the Java virtual machine is erased. Therefore, you cannot use types to match specific Map types.

Case m: Map [String, Int] = >... / / error

/ / can match a general mapping

Case m: Map [, _] = >... / / OK

/ / but as a special case, the type information of the array is intact and can be matched to Array [Int]

Case m: Array [Int] = >... / / OK

3. Match arrays, lists, tuples

Array matching

Val arr1 = Array (1par 1)

Val res = arr1 match {

Case Array (0) = > "0"

/ / match the array containing 0

Case Array (x, y) = > s "$x $y"

/ / match any array with two elements and bind the elements to x and y

Case Array (0, *) = > "0..."

/ / match any array that starts with 0

Case = > "something else"

}

List matching

Val lst = List (1mai 2)

Val res2 = list match {

Case 0:: Nil = > "0"

Case x:: y:: Nil = > x + "" + y

Case 0:: tail = > "0..."

Case = > "something else"

}

Tuple matching

Var pair = (1, 2)

Val res3 = pair match {

Case (0,) = > "0..."

Case (y, 0) = > s "$y 0"

Case _ = > "neither is 0"

}

4.Sealed class (sealed class, alternative)

In Scala, Traits and classes can be modified by the keyword sealed, and after being modified by this keyword, all its subclasses must be defined in the same file.

The advantage of this is that when you use sample classes for pattern matching, you can ask the compiler to make sure that you have listed all possible options and that the compiler can check the integrity of the pattern statements.

Sealed abstract class Furniture

Case class Couch () extends Furniture

Case class Chair () extends Furniture

/ / there is no need to define to match all types at this time

Def findPlaceToSit (piece: Furniture): String = piece match {

Case a: Couch = > "Lie on the couch"

Case b: Chair = > "Sit on the chair"

}

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