Good programmers to share large data Tutorial Series Scala pattern matching, and Sample Class

Good programmers to share large data Tutorial Series Scala pattern matching, and Sample Class
1. Sample class
in Scala sample is a class of special classes, class is immutable sample,
it can be compared to a value that can be used match mode.
The definition of a sample class:
1. Each constructor parameters are val, unless explicitly declared as var
2. companion object provides apply, so you do not use the new keyword will be able to construct the corresponding object
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 target value
point.x
Point. x = 1 // can not
compare the sample values of the class object by:
{IF (== anotherPoint Point)
(. "The Same are" Point + "and" + + anotherPoint) the println
} {the else
the println (+ Point " and "+ + anotherPoint" are different. ")
}
// Point (1,2) and Point (1,2) of the same.

if (point == yetAnotherPoint) {
println(point + " and " + yetAnotherPoint + " are the same.")
} else {
println(point + " and " + yetAnotherPoint + " are different.")
}
// Point(1,2)和Point(2,2)是不同的.
样例类的拷贝
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("[email protected]", "[email protected]", "Me zo o komz gant ma amezeg")
val message5 = message4.copy(sender = message4.recipient, recipient = "[email protected]")
message5.sender // [email protected]
message5.recipient // [email protected]
message5.body // "Me zo o komz gant ma amezeg"
used in pattern matching sample class:
abstract class the Amount
// two samples general class inherits class
Case class Dollar (value: Double) the extends the Amount
Case class the Currency (value: Double, Unit: String) the extends the Amount
Case Nothing the extends the Amount Object
Object CaseClassDemo {

DEF main (args: the Array [String]): Unit = {
Val AMT = new new Dollar (10);
patternMatch (AMT)
}
DEF patternMatch (AMT: the Amount) {
AMT match {
Case Dollar (V) => the println ( "$ "+ V)
Case the Currency (_, U) => the println (" Oh Noes, the I GOT "+ U)
Case Nothing => the println (" Nothing ") // sample object does not ()
}
}
}
statement sample class , the following things will happen automatically:
1. provide unapply way for pattern matching can work
2. generate toString equals hashCode copy method, unless it appears from the definition given by these methods.
2. Pattern Matching
1. Better switch
Scala switch codes in Java-like:
Note:
Scala pattern matching will only match to a branch, do not use the break statement, since it does not fall to the next branch. is an expression match, and if expressions, the values are:
Object PatternDemo {

def main(args: Array[String]): Unit = {
var sign = 0
val ch: Char = 'p'
val valchar = 'p'
var digit = 0

// match expression is
CH {match
Case '+' => = Sign. 1
Case '-' => Sign = -1
// Use | division multiple options
Case '*' | 'X' => Sign = 2
/ / you can use variables
// if the case keyword is followed by a variable name, the expression matches will be assigned to that variable.
Valchar = Case> Sign = 3
// Case similar to Java in the default
// if no pattern matches, will throw MacthError
// mode can be added to guard
Case
IF Character.isDigit (CH) => Character.digit digit = ( CH, 10)
}
the println ( "Sign =" + Sign)
}

}
1 Constant mode (constant patterns) contains variables and constants Constants literals
Scala> Val Site = "Alibaba.com"
Scala> Site match {Case "Alibaba.com" => the println ( "OK")}
Scala> Val = the ALIBABA "Alibaba.com"
// Note here constants must begin with a capital letter
scala> def foo (s: String ) {s match {case ALIBABA => println ( "ok")}}
constants ordinary mode if the comparison of two objects are equal (equals) no difference, and there is nothing to feel the power of
2 variable mode (variable patterns)
Rather simple variable pattern matching process is not to judge, but from the object passed to a new variable name.
scala> site match {case whateverName = > println (whateverName)}
above the site of the object to be matched with whateverName replaced variable name, so it always successful match. But here there is a convention for variables, which calls begins with a lowercase letter, otherwise it will be treated as a constant variable, such as the above whateverName if written WhateverName will find this WhateverName variables, if found is more equality, Can not find the error.
Variable mode is usually not used alone, but when used in combination a plurality of modes, such as
List (1,
X is to the inside of the first element to the match variables marked with x.
3 wildcard pattern (wildcard patterns)
wildcard is underlined: " " can be understood as a particular variable or placeholder. Simple wildcard pattern matching is usually the last line pattern occurs, Case => it matches any object, for processing all other cases the match is not successful. Wildcard patterns often used in combination with other modes:
Scala> List (l, 2,3) match {Case List ( , ,. 3) => the println ( "OK")}
The above List ( , ,. 3) was used 2 represents a wildcard and the second element, these two elements may be any type typically used for a wildcard representing the part is not of interest, it is not a variable mode may be used in the subsequent logical variable.
4. Sample class matches
// class definitions sample
abstract class the Notification
Case In Email class (SENDER: String, title: String, body: String) the extends the Notification
Case class the SMS (Caller: String, Message: String) the extends the Notification
Case class VoiceRecording (contactName: String, link: String ) extends Notification

//基于样例类的模式匹配
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)) //结果:You got an SMS from 12345! Message: Are you there?
println (showNotification (someVoiceRecording)) // result: you Received A Voice Recording from Tom at The Link to the Click Hear IT:! voicerecording.org/id/123
2. guarded mode
to increase the Boolean expression or conditional expression makes the match more specific.
showImportantNotification DEF (Notification: the Notification, importantPeopleInfo: Seq [String]): String = {
Notification match {
// only match email list of contents importantPeople
Case In Email (email,
, ) IF importantPeopleInfo.contains (email) =>
"by You AN Email Special someone from GOT! "
Case the SMS (Number The,
) IF importantPeopleInfo.contains (Number The) =>
" from the SMS by You GOT AN Special someone! "
Case OTHER =>
showNotification (OTHER) // Nothing Special, delegate to Our Original function showNotification
}
}

val importantPeopleInfo = Seq("867-5309", "[email protected]")

val someSms = SMS("867-5309", "Are you there?")
val someVoiceRecording = VoiceRecording("Tom", "voicerecording.org/id/123")
val importantEmail = Email("[email protected]", "Drinks tonight?", "I'm free after 5!")
val importantSms = SMS("867-5309", "I'm here! Where are you?")

the println (showImportantNotification (someSms, importantPeopleInfo))
the println (showImportantNotification (someVoiceRecording, importantPeopleInfo))
the println (showImportantNotification (importantEmail, importantPeopleInfo))
the println (showImportantNotification (importantSms, importantPeopleInfo))
5. The type of matching
may be matched to the type of the expression:
Val ARR the Array = ( "HS",. 1, 2.0, 'A')
Val obj = ARR (Random.nextInt (. 4))
the println (obj)
obj match {
Case X: Int => the println (X)
Case S: String => println (s.toUpperCase)
Case : Double => println (Int.MaxValue)
Case
=> 0
}
Note: when you type in the match, he must be given a variable name, otherwise you will get the object itself to match:
match {obj
Case: BigInt => Int.MaxValue // match any type of object BigInt
case BigInt => -1 // match the object type Class BigInt
}
match occurs at runtime, Java virtual machine of the generic type information is rubbed out. Therefore, you can not type to match a specific type Map.
m Case: the Map [String, Int] => ... // error
// generic mapping can match a
Case m: the Map [
, _] => ... // the OK

// array as a special case, however, the type of information it is intact, can be matched to the Array [Int]
Case m: the Array [Int] => ... // the OK
3. matching arrays, lists, tuples
matching array
val = the array of arr1 (1,1)
Val RES = {match of arr1
Case the array (0) => "0"
// 0 array comprising matching
Case the array (X, Y) => S "$ X $ Y"
// match any array with two elements, and the element is bound to the x and Y
Case the array (0, *) => "0 ..."
// match any array of zero
Case
=> "something the else"
}
A list of matching
Val LST list = (1,2)
Val RES2 = {match list
Case :: Nil 0 => "0"
Case X :: Y :: = Nil> X + "" + Y
Case :: tail 0 => "0 ..."
Case => "something the else"
}
Tuple matching a
var pair = (1,2)
Val RES3 pair match = {
Case (0,
) => "0 ..."
Case (Y, 0) => S "0 $ Y"
Case _ => "neither IS 0"
}
4.Sealed category (sealed class, alternative)
Scala in, Traits and classes can be modified keywords sealed, modified, modified after the keyword, all of its sub-classes must be defined in the same file.
The advantage of this is: When do you use pattern matching sample class, you can let the compiler make sure you have a list of all possible options, the compiler can check the integrity of the model statement.
Furniture's abstract class Sealed
Case class Couch () the extends Furniture's
Case class Chair () the extends Furniture's
// No definition can match this case all types of
DEF findPlaceToSit (piece ...: Furniture's): String = {match piece ...
Case A: Couch => " The Couch ON Lie "
Case B: Chair =>" The Sit is ON Chair "
}

Guess you like

Origin blog.51cto.com/14573321/2444264