In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
[TOC]
The switch statement can be used
1. Scala's powerful pattern matching mechanism can be used in switch statements, type checking and "destructing" and other occasions.
Def swithOps: Unit = {var sign= 0 val ch: Char ='+'ch match {case'+'= > sign= 1 case'-'= > sign=-1 case _ = > sign= 0} println ("sign=== >" + sign)}
In the above code, the case _ pattern corresponds to the default in the switch statement and captures the rest of the situation. If no pattern can match, a MatchError is thrown. And unlike common switch statements, after a pattern match, you need to use break to declare that the branch will not move on to the next branch, which is not required in scala.
2. Match is an expression, not a statement, so there is a return value, so the code can be simplified:
Sign= ch match {case'+'= > 1 case'-'= >-1 case _ = > 0} println ("sign= >" + sign)
You can view the following complete test case:
Pattern matching in package cn.xpleaf.bigdata.p5.cm/** * scala * error: cannot find or load the main class cn.xpleaf.bigdata.p5.`case`.CaseOps * * the problem here lies in using the keyword as part of the class name * so try not to use the keyword as the class name or package name * / object CaseOps {def main ( Args: Array [String]): any expression in Unit = {caseOps2} / * scala has a return value Pattern matching is no exception. We can directly get the corresponding return value for operation * if we do not write the operation of case _, if the match does not match. Relevant exceptions will be thrown: scala.MatchError * / def caseOps2: Unit = {val ch ='1' val sign = ch match {case'+'= > 1 case'-'= > 0 println / case _ = > 2} println (sign)} / * generally, pattern matching is used as a switch case in java * / def caseOps1: Unit = { Val ch ='1' var sign =-1 ch match {case'+'= > sign = 1 case'-'= > sign = 0 case _ = > sign = 2} println (sign)}}
The output is as follows:
2 guards
As a guard for if expressions, the test case is as follows:
Object CaseOps {def main (args: Array [String]): Unit = {caseOps3} / * match pattern matching is used as a guard * / def caseOps3: Unit = {val ch:Char ='a 'var sign =-1 ch match {case' +'= > sign = 1 case'-'= > sign =-1 case _ if Character.isDigit (ch) = > sign = 2 case _ if Character.isAlphabetic (ch) = > sign = 3 case _ = > sign =-2} println ("sign =" + sign)}}
The output is as follows:
Variables in sign = 3 mode
If the case keyword is followed by a variable name, the matching expression is assigned to that variable. Case _ is a special case of this feature, and the variable name is _.
The test case is as follows:
Object CaseOps {def main (args: Array [String]): Unit = {caseOps4} / * the value to be matched is assigned to the variable after case. We can do various operations on the variable * / def caseOps4: Unit = {"Hello, wordl" foreach (c = > println (c match {case'= > "space" case ch = > "Char:" + ch}))}}
The output is as follows:
Char: HChar: eChar: lChar: lChar: oChar:, spaceChar: wChar: oChar: rChar: dChar: l Type pattern
It is better to use pattern matching than to use isInstanceOf to determine types.
Object CaseOps {def main (args: Array [String]): Unit = {caseOps5} / * * use pattern matching instead of isInstanceOf and asInstanceOf to use * / def caseOps5: Unit = {def typeOps (x: Any): Int = {val result = x match {case I: Int = > i case s: String = > Integer.parseInt (s) case z: scala.math.BigInt = > Int .MaxValue case c: Char = > c.toInt case _ = > 0} result} println (typeOps ("12345") = = 12345)}}
The output is as follows:
True matches arrays, lists, and tuples
The test code is as follows:
Object CaseOps {def main (args: Array [String]): Unit = {caseOps6} / * match scala array * / def caseOps6: Unit = {val arr = Array (0,1) arr match {/ / match an array with only one element, and the element is 0 case Array (0) = > println ("0") / / matches any array with two elements And bind the element to x and y case Array (x, y) = > println (x + "" + y) / / match any array case Array (0, _ *) = > println ("0...") that starts with 0. Case _ = > println ("something else")}}
The output is as follows:
0 1 sample class
1. The sample class is a special class that is optimized for pattern matching.
2. Scala provides a special class, which is declared in case class, which can also be called a sample class in Chinese. Case class is actually a bit similar to the concept of JavaBean in Java. That is, only field is defined, and the getter and setter methods are automatically provided by Scala at compile time, but there is no method.
3. The parameters received by the main constructor of case class usually do not need to be decorated with var or val, and Scala will automatically use val modification (but if you use var decoration yourself, you will still follow var)
4. Scala automatically defines the accompanying object, object, for case class, and defines the apply () method, which takes the same parameters in the main constructor and returns the case class object.
The test case is as follows:
Object CaseOps {def main (args: Array [String]): Unit = {caseOps7} / * pattern matching of sample class (case class) * / def caseOps7: Unit = {abstract class Expr case class Var (name:String) extends Expr case class UnOp (operator:String, arg:Expr) extends Expr case class BinOp (operator:String, left:Expr) Right:Expr) extends Expr def test (expr:Expr) = expr match {case Var (name) = > println (s "Var ($name)...") Case UnOp (operator, e) = > println (s "$e... $operator") case BinOp (operator, left, right) = > println (s "$left $operator $right") case _ = > println ("default")} test (BinOp ("+", Var ("1"), Var ("2"))}}
The output is as follows:
Var (1) + Var (2) Simulation enumeration
You can use sample classes to simulate enumerated types:
When using a sample class for pattern matching, you can declare the generic superclass of the sample class as sealed if you want the compiler to ensure that all possible choices are listed.
All subclasses of the sealed class must be defined in the same file as the sealed class.
If a class is sealed, all subclasses are known at compile time, so you can check the integrity of the schema statement.
It is a good idea to have all sample classes in the same group extend a sealed class or attribute.
Sealed abstract class TrafficLightColorcase object Red extends TrafficLightColorcase object Yellow extends TrafficLightColorcase object Green extends TrafficLightColordef typeOps (color:TrafficLightColor): Unit = {color match {case Red = > println ("stop") case Yellow = > println ("hurry up") case Green = > println ("go")}} def verityTypeOps: Unit = {typeOps (Red)} Option type
1. The Option type is used to represent values that may or may not exist. The sample class Some wraps a value, while the sample object None indicates no value. Option supports generics. (so here, as above, is the operation of the sample class)
2. The syntax of Option must be mastered, because there are a large number of examples of Option syntax in the Spark source code.
The test case is as follows:
Object CaseOps {def main (args: Array [String]): Unit = {caseOps8} def caseOps8: Unit = {def optionOps: Unit = {val capitals = Map ("France"-> "Paris", "Japan"-> "Tokyo" "BeiJing"-> "Tongzhou") println (capitals.get ("Japan") + show (capitals.get ("Japan")) println (capitals.get ("BeiJing") + show (capitals.get ("India"))} def show (x: Option [String]) = x match {case Some (s) = > s case None = > "?"} optionOps}}
The output is as follows:
Some (Tokyo) TokyoSome?
3 、 getOrElse
The following is an example of how to use getOrElse () to access a value or use a default value when there is no value:
Val a:Option [Int] = Some (5) val b:Option [Int] = Noneprintln ("a.getOrElse (0):" + a.getOrElse (0)) println ("b.getOrElse (10):" + b.getOrElse (10))
4. Use the isEmpty () method:
Println ("a.isEmpty:" + a.isEmpty) println ("b.isEmpty:" + b.isEmpty)
The tests are as follows:
Scala > val a:Option [Int] = Some (5) a:Option [Int] = Some (5) scala > val b:Option [Int] = Noneb: Option [Int] = Nonescala > a.getOrElse (0) res5: Int = 5scala > ares6: Option [Int] = Some (5) scala > b.getOrElse (10) res9: Int = 10scala > a.isEmptyres7: Boolean = falsescala > b.isEmptyres8: Boolean = true
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.