Conditional expressions
In Scala, the If/else expression is a value, and this is the value of an expression that follows if or else. For example:
Val s = if (x > 0) 1 else-1//similar to var s = 0if (x > 0) s = 1 else s =-1
Scala allows you to use mixed-type return values , such as:
if (x > 0) "Positive" else-1
The types returned by the above expressions are public super-types of their type, where java.lang.String and Int are the public superclassof any. If the Else section is missing, for example:
if (x > 0) 1//This is equivalent to if (x > 0) 1 Else ()
This is equivalent to introducing a unit class that writes (). You can think of () as a placeholder for "no useful value", and the Unit as void in C + + or java. ( but technically, void has no value, but the unit is a value that represents a value of "no value" ).
In addition, Scala does not have a switch statement, but it has a powerful pattern-matching mechanism.
Tip: If you want to paste blocks of code in REPL, you can use paste mode, type :p aste , paste the code block in, and then press CTRL + D
statement termination
In C + + and Java, each statement ends with a semicolon, otherwise it is not compiled, and in Scala, the position of the end of the line does not require a semicolon , but when you write multiple statements in a single line , you need to separate them with semicolons . For example:
if (n > 0) {r = R * N; n-= 1}
If you are writing longer sentences that need to be written in two lines, make sure that the first line ends with a symbol that cannot be terminated, for example:
s = S0 + (v-v0) * t +//+ tell parser here is not the end of the statement 0.5 * (a-a0) * t * t
Block Expressions and Assignments
In Scala, the {} block contains a series of expressions, and the result is an expression, that is, the value of the last expression in the block is the value of the block. This allows you to initialize Val directly with the value of the block.
Val dis={val dx=x=x0;val dy=y-y0; sqrt (dx*dx+dy*dy)}
The value of the last expression is unit, so the value of the entire block is the unit, not the value of N. So, the assignment operation cannot be used this way: X=y=1, because y may be a unitInput and output
PRINT/PRINTLN Print to the console.
Print ("Answer:") println printf ("Hello,%s! You are%d years old.\n "," Fred "," a ")//C-style formatted string
UseReadLine reading a line of input from the console。 If you want to read numbers, Boolean, or characters, you can use Readint, readdouble, ReadByte, Readshort, Readlong, Readfloat, Readboolean, ReadChar. Cycle
While and do loops in Scala are the same as C + + and Java. But Scala does not have a structure that directly corresponds to a for (initialize variable; Check whether a variable satisfies a condition; update a variable) .
This causes I to iterate through all the values of the right-hand expression. The type of the variable is not specified in the For loop, and the type of the variable is the type of the element of the collection. You can use the until method instead of the to method if you want to get to the left-hand-open interval:
val s = "Hello" var sum = 0for (i <-0 until s.length) sum + = s (i)//equivalent to <span style= "Background-color:rgb (255, 2 55, 51); " >var sum = 0for (ch <-"Hello") sum + = ch</span>
Note: There are no break or continue to exit the loop in Scala, there are several options for the alternative:
1. Using a Boolean control variable
2. Using nested functions-you can return from a function;
3. Use the break method in the Breaks object:
Import scala.util.control.breaks._breakable {for (...) { if (...) break; Exit breakable block ... }}
Advanced for loop and for-deduction
Scala offers advanced applications for loops: You can provide multiple generators in the form of variable <-expressions , separating them with semicolons . For example:
for (I <-1 to 3, J <-1 to 3) print ((Ten * i + j) + "")
Scala can take a guard for each generator, with a Boolean expression that starts with an if:
for (I <-1 to 3, J <-1 to 3 if I! = j) Print ((Ten * i + j) + "")
If the loop body of a Scala for loop starts with yield, the loop constructs a collection , each iteration generating a value in the collection:
for (I <-1 to ten) yield I% 3
This type of loop is called a for deduction. The set generated by the for deduction is type-compatible with its first generator.
for (c <-"Hello", I <-0 to 1) yield (c + i). Tocharfor (i <-0 to 1; C <-"Hello") yiels (c + i). ToChar
For a For loop with multiple expressions, you can also use {} to enclose expressions, guards, and definitions in curly braces, separating them with a newline instead of a semicolon:
For {i <-1 to 3 from = 4-i J <-from to 3}print ((10*i+j) + " ")//Print 13 22 23 31 32 33
Function
Object-oriented programming is supported in Scala, and functional programming is supported. As a result, Scala supports functions in addition to party Add. The method is to manipulate the object, not the function. C + + also has functions, and in Java we can only use static methods to simulate.
The definition function needs to include: function name, parameter, and function body:
def abs (x:double) = if (x >= 0) x else-x
You must give the type of the arguments in all the functions . However, as long as the function is not recursive, you do not need to specify the return type .
The function body, which is the last expression of the code block, is the return value of the function :
def FAC (n:int) = { var R = 1 for (i <-1 to n) R = R * I R}
For recursive functions:
def FAC (n:int): <span style= "Background-color:rgb (255, 255, 0);" > int</span> = if (n <= 0) 1 Else n * FAC (N-1)
If there is no return type, the Scala compiler cannot verify that the type of n * FAC (n-1) is int
Default parameters and named parameters
and C + +, Java-like, Scala also provides default parameters, such as:
def decorate (str:string, left:string = "[", right:string = "]") = left + str +right
Decorate ("hello") outputs [Hello]. Scala also implements specifying parameter names when calling a function, so that it does not have to follow the order of the arguments when the function is defined: decorate (left = "<<<", str = "Hello", and right = ">>>"). The name parameter is useful in C + +, if you want the right parameter to use the value you specify, you must also specify the left value, even if you continue to use "[", because the default parameter in C + + cannot be used in the middle, and Scala can use a named parameter implementation to specify a parameter, For example: Decorate ("Hello", right = "]<<<") will output [hello]<<<
Variable length parameter
How to implement variable-length parameters in Scala:
def sum (args:int*) = { var result = 0 for (arg <-args) result + = arg result}
The function is given a parameter of type seq. If you already have a sequence of values, you cannot pass it directly to the function above, and if the SUM function is called when a single argument is passed in, then the argument must be a single integer, not an integer interval.
For recursive functions:
def recursivesum (args:int): Int = { if (args.length = = 0) 0 else Args.head + recursivesum (args.tail: _*)}
Note: One common use in variable-length parameters is when a Java method that has a parameter type of object, such as printstream.printf or Messageformat.format, needs to be manually transformed by a primitive type:
Val str = Messageformat.format ("The answer to {0} is {1}", "Everything", 42.asinstanceof[anyref])
Process
Scala has a special way of representing functions that do not return a value. If the function body is enclosed in curly braces but there is no preceding ' = ', then the return type is unit. such a function is called a procedure. However, it is recommended that you add the return value unit to facilitate reading:
def box (s:string): Unit = { ...}
Lazy value
In Scala, when Val is declared as lazy, its initialization is deferred until we first value it. For example:
<span style= "Background-color:rgb (255, 255, 51); >lazy</span> val words = Scala.io.Source.fromFile ("/usr/share/dict/words"). mkstring
If the program never accesses words, then the file will not be opened . Lazy values are useful for expensive initialization statements.
Note: The lazy value is an extra cost, each time we access the lazy value, there will be a method is called, and this method will be in a thread-safe way to check whether the value has been initialized.
Abnormal
Scala exceptions work in the same way as Java or C + +. For example:
throw new IllegalArgumentException ("X should not being negative")
Unlike Java, Scala has no "inspected" exceptions -you don't have to declare that a function or method might throw some kind of exception. The throw expression has a special type of nothing. This is useful in if/else expressions, if the type of a branch is nothing, then the type of the If/else expression is the type of another branch, for example:
if (x >= 0) { sqrt (x)} else { throw new IllegalArgumentException ("X should not is negative")}
Then the type of the If/else expression is double.
The syntax for catching exceptions takes the syntax of pattern matching, which is described later, for example:
try { process (new URL ("Http://horstmann.com/fred-tiny.gif")} catch {case _: malformedurlexeception = println ("Bad URL:" + URL) case ex:ioexception = Ex.printstacktrace ()}
As with C + +, Java, more generic exceptions should be followed by more specific exceptions. Note that if you do not need to use the caught exception object, you can use _ instead of the variable name.
The try/finally statement allows you to release resources, whether or not an exception occurs, such as:
var in = new URL ("Http://horstmann.com/fred-tiny.gif"). OpenStream () try { process (in)} finally { in.close ()}
Learn the Scala chapter 2nd – Control structure and function notes