Learn Scala 2

Source: Internet
Author: User

Control structures and functions

1. In Scala, almost all constructed grammatical structures have values . This feature is designed to make the program more streamlined and easier to read.

(1) If expression has value

(2) The block also has a value--is the value of its last expression

(3) Scala's for loop is like the "enhanced" Java for loop

(4) semicolons (in most cases) are not required

(5) void type is unit

(6) Avoid using return in function definition

(7) Be careful not to omit the function definition.

(8) The exception works in the same way as in Java, unlike the use of "pattern matching" in a catch statement

(9) Scala has no exception to be inspected

2. Conditional expressions

In Scala, the If/else expression has a value, which is the value of an expression that follows the if or else. For example:

if (x > 0) 1 else-1

You can assign the value of an if/else expression to a variable:

Val s = if (x > 0) 1 else-1

This is the same as the effect of the following statement:

if (x > 0) s = 1 else s =-1

However, the first notation is given, because it can be used to initialize a Val, and in the second notation, s must be var.

Each expression in Scala has a type. For example, the type of the expression if (x > 0) 1 else-1 is int, because the type of the two branches is int. Mixed type expressions, such as if (X > 0) "Positive" else-1, the type of the expression above is a public super-type of another branch type. The public super-type of java.lang.String and int is called any.

If the else part is missing, for example: if (x > 0) 1, then it is possible that the IF statement has no output value. But in Scala, each expression should have some sort of value . The solution is to introduce a unit class that writes (). If statement without else equals: if (x > 0) 1 Else ()

Consider () as a placeholder for "no useful value", and the unit as void in Java.

  Scala does not have a switch statement , but it has a much stronger pattern-matching mechanism. At this stage, it is better to use a series of if statements.

3.REPL is more "myopic" than the compiler- it can only see one line of code at a time . Available curly braces:

if (x > 0) {1

} else if (x = = 0) 0 else-1

This concern is only available in REPL. Paste the block code in the REPL, which can be used in paste mode. Type:: Paste paste the code block in and press Ctrl+d. This way the REPL will parse the code block as a whole.

4. Statement termination

In Scala-similar to JavaScript and other scripting languages-the position of the end of the line does not require a semicolon. However, if you want to 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 write a long statement that needs to be written in two lines, make sure that the first line ends with a symbol that cannot be used to end the statement. In general, a good choice is an operator:

s = S0 + (v-v0) * t +//+ tells the parser that this is not the end of the statement

0.5 * (a-a0) * t * t

If you tend to use semicolons, that's it--they don't hurt.

5. Block Expressions and Assignments

In Java, a statement block is a sequence of statements contained in {}. In Scala, {} quickly contains a series of expressions, and the result is an expression. The value of the last expression in the block is the value of the block.

This feature is useful for scenarios in which Val initialization takes a lot of steps to complete. For example:

Val distance = {val dx = x-x0; val dy = y-y0; sqrt (DX * dx, dy * dy) }

  In Scala, the assignment action itself has no value-or, more strictly, the value of the unit type.

A block that ends with an assignment statement, such as {r = R * N; the value of N-=1} is a unit type. We need to be aware of this when we define a function.

6. Input and output

 If you want to print a value, use the print or println function. In addition, there is a printf function with a C-style formatted string:

printf ("Hello",%s! You are%d-old. \ n "," Fred "," a ")//Hello, fred! You are a.

Use the ReadLine function to read a line of input from the console. You can also use Readint, readdouble, ReadByte, Readshort, Readlong, Readfloat, Readboolean, ReadChar. However, ReadLine takes a parameter as a hint string:

Val name = ReadLine ("Your Name:")

Print ("Your Age:")

Val age = ReadInt ()

printf ("Hello,%s! Next year, you'll be%d. \ n, name, age + 1)

7. Cycle

Scala has the same while and do loops as Java and C + +. For example:

while (n > 0) {

R = R * N;



Scala does not have a structure that directly corresponds to a for (initialize variable; Check whether a variable satisfies a condition; update a variable). If you need such a loop, there are two options: one is to use the while loop, and the other is to use the following for statement:

    the for (I <-expression) lets the variable i traverse all the values of the expression on the right side of <-. as to how this traversal is performed, it depends on the type of expression. For range, this loop causes I to get each value in the interval at once.

For example:

for (i <-1 to N)

R = R * I

When iterating through arrays and strings, you need a range of 0 to n-1, and you can use the until method instead of the to method. The Util method returns an interval that does not contain an upper bound.

val s = "Hello"

var sum = 0

for (i <-0 util s.length)//[0,s.length-1]

No break or continue statements are provided in Scala to exit the loop. If a break statement is required:

(1) using a Boolean control variable

(2) using nested functions--return from function

(3) Use the break method in the Breaks object:

Import Scala.util.control.breaks._

breakable {

For (...) {

if (...) break;




Here, the transfer of control is done by throwing and catching exceptions, so if time is important, try to avoid using this mechanism.

8. Advanced for loop and for-deduction

(1) You can provide multiple generators in the form of a variable <-expression , separating them with semicolons.

for (I <-1 to 3; J <-1 to 3) print ((Ten * i + j) + "")//Print 11 12 13 21 22 23 31 32 33

Each generator can take a guard with a Boolean expression that begins with an if :

for (I <-1 to 3; J <-1 to 3 if I! = j) Print ((Ten * i + j) + "")//Print 12 13 21 23 31 32

Note If there is no semicolon before .

You can use any number of definitions to introduce variables that you can use in a loop:

for (I <-1 to 3; from = 4-i; J <- from to 3) print ((Ten * i + j) + "")//Print 13 22 23 31 32 33

  if the loop body of the For loop starts with yield , the loop constructs a collection that each iteration produces a value in the collection:

For (1 <-1 to ten) yield i% 3

Vector generation (1, 2, 0, 1, 2, 0, 1, 2, 0, 1)

This type of loop is called a for deduction .

The for push-to-build collection is type-compatible with its first generator .

for (c <-"Hello"; I <-0 to 1) yield (c + i). ToChar//will generate "Hieflmlmop"

for (i <-0 to 1; C <-"Hello") yield (c + i). ToChar//will generate vectors (' H ', ' e ', ' l ', ' l ', ' o ', ' I ', ' f ', ' m ', ' m ', ' P ')

You can also include generators, guards, and definitions in curly braces, and you can separate them with a newline instead of a semicolon:

for{I <-1 to 3

From = 4-i

J <-from to 3}

9. Functions

Scala supports functions in addition to methods. method operates on an object, not a function . In Java, however, we can only use static methods to simulate.

  define the function , give the name of the function, the parameters and the function body, for example:

def ABS (x:double) = if (x >= 0) x else-x

    the type of all parameters must be given . as long as the function is not recursive, you do not have to specify a return value type . The Scala compiler can infer the return value type through an expression on the right side of the = symbol.

If a function body requires more than one expression to complete, you can use a block of code. The value of the last expression in the block is the return value of the function. For example:

def FAC (n:int) = {

var r = 1

for (i <-1 to n) R = R * I

R//return value of R


For recursive functions, a return value type must be established. For example:

def FAC (n:int) : Int = 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.

10. Default parameters and named parameters

When you call some functions , you do not explicitly give all the parameter values, and you can use the default parameters for these functions . For example

def decorate (str:string, left:string = "[", right:string = "]") =

Left + str + right

The two parameters of this function are left and right with the default value "[" and "]". Call Decorate ("Hello") to get "[Hello]".

If you want to count the number of parameters, you give not enough values, the default parameters will be applied one by one in the back. For example, decorate ("Hello", ">>[") uses the default value of the right parameter.

The parameter name can be specified when supplying the parameter value, for example: Decorate (left= "", str = "Hello", right= ""), and the result is "Hello". Note that the named parameter does not need to be exactly the same as the order of the argument list. The name parameter makes the function more readable.

  You can mix unnamed and named parameters, as long as those unnamed parameters are in the front row.

Decorate ("Hello", right = "}>>"//Will call decorate ("Hello", "[", "}>>")

11. Variable Length Parameters

It is more convenient to implement a function that accepts a variable-length parameter list.

def sum (args:int*) = {

var result = 0

for (Arg <-args) result + = arg



The function can be called with any number of arguments: val s = SUM (1, 4, 9, 16, 25)

If you already have a sequence of values, you cannot pass it to the above function. For example: Val s = SUM (1 to 5)// error

 If the SUM function is called to pass in a single argument, the argument must be a single integer, not an integer interval. Solution: Tell the compiler that you want this parameter to be treated as a parameter sequence. Append: _*

val s = SUM (1 to 5: _*)//treat 1 to 5 as parameter sequence

Learn Scala 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.