1. Matching pattern
- Summary
- Similar to switch...case in java, but much more powerful and flexible.
- The goal is to solve the matching and processing problems when a pattern (value is also one of the patterns) is met.
- Instructions
- A pattern match consists of a series of alternatives, each starting with the keyword case. Each alternative contains a pattern and one or more expressions. The arrow symbol **=>** separates the pattern from the expression.
- Selector match {alternative}, the match expression completes the calculation by trying each pattern in code order, and the remaining cases will not continue to match as long as a matching case is found.
Example
Homotype
def main(args: Array[String]) { println(selfMatch("javase")) } def selfMatch(x: String): String = x match { case "javase" => "Java Develop Standard Edition" case "javaee" => "Java Develop Enterprise Edition" case _ => "Other Java Edition " }
Different types
def main(args: Array[String]) { println(selfMatch("one")) println(selfMatch(2)) println(selfMatch("III")) println(selfMatch("five")) } def selfMatch(x: Any): Any = x match { case "one" => 1 case 2 => "two" case "III" => "Greek Number 3" case _ => "Other unknown" }
Example of complex expression matching
def main(args: Array[String]) { println(selfMatch(1)) println(selfMatch(10)) println(selfMatch(22)) println(selfMatch(78)) } def selfMatch(x: Int): String = x match { case _ if x < 12 => "Childhood" case _ if x < 18 => "Under age" case _ if x >= 18 && x < 60 => "adult" case _ => "Already old!" }
Example of type pattern matching
def main(args: Array[String]) { println(selfMatch(1)) println(selfMatch("10")) println(selfMatch(new TestPatternMatch())) println(selfMatch(new Object())) } def selfMatch(x: Any): Any = x match { case _: Int => "What's passed in is an integer" case _: String => "String passed in" case _: TestPatternMatch => "The data type passed in is TestPatternMatch" case _ => "Don't know what type" } //Define an empty class for easy type pattern matching on top class TestPatternMatch { }
2. Regular expressions
- Summary
- Same as regular expressions in Java
- Use "".r or the Regex class in the scala.util.matching package to abstract support for regularity.
- common method
- findAllIn: Find all matches
- mkString: A string that connects the matching results of a regular expression
- Regularly you can use pipes (|) to set different modes
Example
//Define a string as a regular expression val pattern1 = "The Eighteenth National Congress of the CPC".r //Regular source string to unmatch val str1 = "The 18th National Congress is an important and landmark meeting!" //Find the value of the first matching pattern regular expression in the source string println(pattern1 findFirstIn str1)//Some(18th National Congress) //Define a string as a regular expression val pattern2 = new Regex("(eighteen|18)large") //Regular source string to unmatch val str2 = "The 18th National Congress is an important and landmark meeting,18 Since then, remarkable progress and achievements have been made in all walks of life!" //Find all values in the source string that match the pattern regular expression println((pattern2 findAllIn str2).mkString(","))
3. Exception handling
- Summary
- The exception handling mechanism is similar to that of the Java language. The exception classes are also Java classes and are not overridden
- It mainly includes exception throwing and exception catching.
- Throw an exception with throw, declaring that possible exceptions are different from Java, using annotated @throws(classOf[SomeException])
- Catch exceptions in the form of try...catch pattern matching
- There is no need to catch check exceptions in Scala: checked exception s, or declare them in the throws clause. A throws clause can be declared with the @throws label, but this is not necessary. The biggest problem with this mechanism is that if an exception is encountered and no catch is made, the program will terminate. If a catch is made, it can proceed in a programmatic manner, but it must not be stopped.
Example
//Exception thrown within method def f(){ throw new Exception("Test exception throw!"); } //Declare to throw an exception when the method is defined @throws(classOf[Exception]) def callMe() = { println("i am in callMe method") } //Catch Exceptions try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException => { println("Sorry, the file was not found!") } case ex: IOException => { println("Unexplained IO abnormal!") } } finally { println("whether try...catch How, it will be executed finally,I am here finally in!") }
4. Extractors
- Summary
- The extractor extracts the parameters that construct the object from the object passed to it.
- The extractor is an object with an unapply method. The unapply method is the reverse operation of the apply method: unapply accepts an object and then extracts the value from it, which is usually used to construct the value of the object.
- The apply and unapply methods are inverse. Apply is used to construct an object without using the new method. unapply is used to decompose the object in reverse and extract its corresponding parameter values.
Example
def main(args: Array[String]) { var obj = apply("antg", "192.168.1.33"); println("Apply Method Forms an Object: " + obj); println("Unapply Method retrieves parameters from the object:" + unapply(obj)); println("Unapply Method retrieves parameters from the object: " + unapply("I am not an landing address")); } // Injection method (optional) def apply(username: String, ip: String) = { username + "@" + ip } // Extraction method (required) def unapply(str: String): Option[(String, String)] = { val parts = str split "@" if (parts.length == 2) { Some(parts(0), parts(1)) } else { None } }
Extractor matches pattern
def main(args: Array[String]) { //Automatically invoke the apply method of TestUnapplyPatternMatch val loginInfo = TestFunction("antg", "192.168.1.33") println(loginInfo) loginInfo match { //unapply is called automatically case TestFunction(username, ip) => println(username + "Logged on" + ip + " This machine!") case _ => println(loginInfo) } } def apply(username: String, ip: String) = username + "@" + ip def unapply(loginInfo: String): Option[(String, String)] = { val parts = loginInfo split "@" if (parts.length == 2) { Some(parts(0), parts(1)) } else { None } }
V. Document IO
- Summary
- Basically similar to java
- Its file write operations, directly using the I/O class in java
- A few new IO classes have been added and some simplification has been made in the API
Example
Write string to specified file
def main(args: Array[String]) { val writer = new FileOutputStream(new File("output.txt")) writer.write("antg".getBytes("utf-8")) writer.close() println("done") }
Read user input from console
def main(args: Array[String]) { print("What you want to say to yourself now: ") var line = ""; //scala supports the introduction of packages in code blocks import scala.util.control.Breaks._ var br = new BufferedReader(new InputStreamReader(System.in, "utf-8")) //To use break, you must wrap it in a breakable breakable { line = br.readLine() while (line != null) { if (line equals "exit") { break } println(line) line = br.readLine() } } br.close() println("done") }
Read content from a file
def main(args: Array[String]) { println("Read the contents of the file as:") println("First way---------") var fileSource = Source.fromFile("output.txt", "utf-8") for (line <- fileSource.getLines) { println(line) } println("Second way---------") Source.fromFile("output.txt", "utf-8").foreach { print _ } println("Third way---------") fileSource = Source.fromFile("output.txt", "utf-8") fileSource.foreach(print) }