An If expression
Scala's if works the same as in many other languages. It tests a state and, according to whether it is true, executes one of the two branches:
var filename = "Default.txt"if (! Args.isempty) = args (0)
Since Scala's if is an expression that can return a value, it can be changed to a more functional style with Val:
val filename = if (!args.isempty) args (0) Else "Default.txt"
The 2nd advantage of using Val instead of Var is that he is better able to support the equivalent inference:equational reasoning. In the absence of side effects of an expression, the introduced variable is equivalent to the expression that evaluates it. Therefore, you can substitute the variable name with an expression whenever:
println (ifelse "Default.txt")
While loop
Scala's while loop behaves the same as in other languages. Includes a state and a loop body, as long as the state is true, the loop body is executed over and over:
def gcdloop (X:long, y:long): Long = { = x = y while (A! = 0 ) { /c7>= a = b% a = temp } B}
Scala also has a do-while loop. In addition to moving the state test from the front to the back, there is no difference from the while loop.
While and do-while structures are called "loops", not expressions, because they do not produce meaningful results, and the type of the result is Unit. Indicates the type of value produced is Unit. Called unit value, write (). The existence of a Scala Unit differs from the void in Java:
Cala> def greet () {println ("HI")}greet: () Unitscala> Greet () ==true
Because the method body does not have an equal sign before it, greet is defined as the process of the result type Unit. Therefore, greet returns the unit value () so that in comparison with the greet result and the unit value (), the equality of the output is true.
For expression Enumeration Collection class
The simplest thing to do with for is to enumerate through all the elements of a collection class:
Val fileshere = (new java.io.File (".") ) . Listfiles for (file <- fileshere) println (file)
The code first creates a file that points to the current directory ".", calls the Listfiles method, and returns an array of file objects stored in the Fileshere variable, by Generator: Generator The syntax "file <-fileshere" iterates through the elements of Fileshere, and each time the new Val that enumerates the file is initialized and printed by the element value.
The FOR expression syntax is valid for any kind of collection class, not just an array, you can create a Range with a syntax like "1 to 5" and then use the For enumeration:
for (I <-1 to 4) | println ("lteration" + i) Lteration1lteration2lteration3lteration4
Filter
There are times when you do not want to enumerate all the elements of a collection class. Instead, you want to filter out a subset. You can do this by adding the filter: Filter: An IF clause to the for parenthesis:
Val fileshere = (new java.io.File (".") ) . Listfilesforif file.getName.endsWith (". Scala")) println (file)
You can also write this:
for (File <- fileshere) if (File.getName.endsWith (". Scala")) println (file)
If you want, you can include more filters. Just keep adding to the clause:
for ( <- fileshere if file.isfile; if file.getName.endsWith (". Scala")) println (file)
If more than one filter is added to the generator, the IF clause must be separated by semicolons.
Nested enumerations
If more than one <-clause is added, a nested "loop" is obtained:
def filelines (file:java.io.File) = = for { <- fileshere if file.getName.endsWith (". Scala") <- filelines (file) if line.trim.matches (pattern) + ":" + Line.trim) grep (". *gcd.*")
The for expression that the code demonstrates has two nested loops, the outer loop enumerates Fileshere, and the inner layer enumerates all Filelines (file) files that end in. Scala. You can use braces instead of parentheses around generators and filters, and the advantage is that you can omit some semicolons that you must add with parentheses.
Mid-stream (flow room) variable binding
Notice the repetition of the expression in the previous Code Line.trim, which is not a negligible calculation, if you want to calculate only once each time, you can use the equal sign (=) to bind the result to a new variable to do this, the bound variable is used as Val introduced and used, but without the keyword val:
def grep (pattern:string) = for { <- fileshere if File.getName.endsWith (". Scala") <- filelines (file) = Line.trim if trimmed.matches (pattern) + ":" + Trimmed) grep (". *gcd.*")
A variable named trimmed is introduced for the for expression and is initialized to the result value of Line.trim. The for expression can then use the new variable in two places, once in the If, once in println.
Create a new collection
You can create a value to remember each iteration, as long as you precede the for expression with the keyword yield:
def scalafiles = for { <- fileshere if file.getName.endsWith (". Scala ") } yield file
The for expression creates a value each time it executes, and when the for expression finishes, the result is a collection containing all the resulting values, and the type of the resulting collection is based on the collection type processed by the enumeration clause. For-yield The syntax of an expression:
for {clause} yield {loop body}
Yield before the entire loop body, even if the loop body is a block of code surrounded by braces, make sure that yield is placed before the opening parenthesis rather than the last expression of the code:
for if file.getName.endsWith (". Scala")) { //}
Using a try expression to handle exception throwing exceptions
The exception is thrown to look exactly like Java. First create an exception object and throw it with the Throw keyword:
Throw New IllegalArgumentException
In Scala, throw is an expression of the result type, and the type of throw exception is nothing, although throw does not actually derive any value, but it can still be used as an expression.
Catching exceptions
The syntax used to catch exceptions is as follows:
ImportJava.io.FileReaderImportjava.io.FileNotFoundExceptionImportjava.io.IOExceptionTry{val F=NewFileReader ("Input.txt") //Use and close file}Catch { CaseEx:filenotfoundexception =//Handle Missing File CaseEx:ioexception =//Handle Other I/O error}
The behavior of this try-catch expression is consistent with exception handling in other languages. The program body is executed, and if an exception is thrown, each catch clause is tried in turn. In this case, if the exception is FileNotFoundException, then the first clause is executed. If it is a IOException type, the second clause will be executed. If not, then Try-catch will end up and raise the anomaly.
Finally clause
Like most other Scala control structures, try-catch-finally also produces values. Scala's behavior differs from Java only in that Java's try-finally does not produce a value. In Java, if the finally clause contains an explicit return statement, or throws an exception, the return value or exception will "override" above any value or exception that originated from the try code block or some of its catch clauses:
Try return finally return 2}
Calling F () produces a result value of 2, instead:
Try finally {2}
Call G () to generate 1.
Match expression
Scala's match expressions allow you to choose from a number of options:alternative , like switch statements in other languages. The Match expression allows you to use any pattern:pattern to choose:
if Else " firstarg Match { case" salt "= println (" Pepper ") case" chips "= println ("Salsa") case "eggs" = println ("bacon") Case _ = println ("Huh?") )}
The match default is indicated by an underscore (_), which is a wildcard character commonly used in Scala as a placeholder for completely unclear values.
The case matching expression in Scala can make any kind of constant, with each optional last without a break, but the break is implied. Match expressions can also produce values:
if Else "= firstarg Match { case" salt "+" pepper "case " chips "=" Salsa "Case " eggs "=" bacon "Case _ =" Huh? " }println (friend)
Variable Range
The definition of a variable in a Scala program has a scopethat can be used:scope. Curly braces usually introduce a new scope, and anything defined in curly braces is separated from the range after the parentheses.
Once a variable is defined, the same name cannot be defined within the same scope, but a variable with the same name as the outer scope can be defined within the inner scope, which is the inner scope enclosed in curly braces. An internal variable obscures an external variable with the same name.
Scala Programming (iv) built-in control structure