Programming in Scala Reading Note 6

Source: Internet
Author: User
Tags new set
Built-in control structures built-in control structure 1 if control structure

Scala's if structure is the same as that of Java, and the function is not much different. Scala's saying is that if can return a value

Val filename = If (! Args. isempty) ARGs (0) else "default.txt"

This statement is relatively common, but a VaR is not introduced here, but the Val is used.

Println (filename) is equivalent to println (if (! Args. isempty) ARGs (0) else "default.txt"), which is also an advantage of Val, called equational Reasoning


2 Loop Structure

Do {...} while (condition)

While (condition ){...}

It is basically the same as Java, but here we need to note that the return value of the value assignment statement is unit rather than the assigned value, for example:

VaR newline: String = ""

While (newline = Readline ())! = ""){...}

If the returned value of Readline () in Java is "", this condtion is incorrect and will jump out.

In Scala, the return value of the value assignment statement is unit, which is never equal to "", so it will never terminate.

Because loop does not return a value, it does not appear in functional language. Instead, it uses recursion:

Def greatestcommondivisor (A: int, B: INT): Int =

If (B = 0) A else greatestcommondivisor (B, B %)


3. For Structure

Traverse a set

For (File <-files ){...}

File <-files is called generator. It is used to define a var variable named file and assign it a series of values for a for loop.

<-The expression on the right is generator expression, which is used to generate a series of values.

Generator expression can be a collection of any form

1 to 5: range (1, 2, 3, 4, 5)

1 until 5: range (1, 2, 3, 4)

Filter set

When processing only the set elements that meet certain conditions, such:

For (File <-FilesIf file. getname. endswith (". Scala ")){...}

Multiple conditions:

For (

File <-Files

If file. isfile // No (), no; or,

  If file. getname. endswith (". Scala ")


It does not contain any commas (,) or semicolons (;).

I believe this is handsome...

Nested loop

For (

File <-Files

  If file. isfile // No (), no; or,

If file. getname. endswith (". Scala "); // Pay attention to this semicolon !!!

  Line <-scala. Io. Source. fromfile (file). getlines. tolist

If line. Trim. Match (". * GCD .*")


The for body can contain the current file information and the current line information...

If you want to remove this, we can replace the parentheses after for with braces.

For {

File <-Files

  If file. isfile // No (), no; or,

If file. getname. endswith (". Scala") // There is no semicolon here, because we use braces {}

  Line <-scala. Io. Source. fromfile (file). getlines. tolist

If line. Trim. Match (". * GCD .*")


CirculatingBind Variable

For (

File <-Files

  If file. isfile // No (), no; or,

If file. getname. endswith (". Scala ");

Line <-scala. Io. Source. fromfile (file). getlines. tolist

Trimmed = line. Trim

If trimmed. Match (". * GCD .*")


The trimmed introduced is a Val, which can be used in subsequent code.

For loop to generate a new set variable

For krasesYieldBody

First, attention should be paid to the location of the yield, after the for condition, before the for body,

For {condition...} yield {for body}

This for statement can return a set of objects.


4 try

Exception: When an exception occurs, it will be ruthlessly thrown, and the exception will return according to the call sequence of the method call stack until a method handles the exception, otherwise, it will be traced back to the last method and then thrown to the compiler.

Throw expression

Throw new illegalargumentexception generates an error parameter exception, that is, the throw statement returns a value.

val half =  if (n % 2 == 0)    n / 2  else    throw new RuntimeException("n must be even")

In the above Code, if the N passed in is not an even number, a runtime exception will be thrown. This exception will be processed, resulting in no half value and no initialization. So any program that wants to use this half will have no problem.

Catch expression

Catch statements are used to maintain consistency with pattern matching, a very important concept in Scala.

try {  val f = new FileReader("input.txt")  // Use and close file} catch {  case ex: FileNotFoundException => // Handle missing file  case ex: IOException => // Handle other I/O error}

Each case in catch represents a situation. The Compiler checks whether its type is of the specified type. If yes, execute the following statement. If it does not continue until the corresponding exception type is found, if none of the above conditions are met, the catch statement is terminated and an exception is thrown to the method caller.

Finally expression

It is basically an expression set for side effects.

The result is that of the try clause if no exception is thrown, or the relevant catch clause if an exception is thrown and caught.

If an exception is thrown but not caught, the expression has no result at all.

The value computed in the finally clause, if there is one, is dropped.

Try-catch-finally expression value:

If no exception is thrown, the value is the value of the try expression.

If an exception is thrown and caught by catch, it is the value of the exception capture statement.

If an exception is thrown and not captured, this expression has no value. Instead of finally values.

Although the finally statement contains the expression return value, its value is also discarded.


It is cruel and hard to understand. Scala provides an explanation that the finally statement is used:

1. Close an object

2. Close a socket

3. Close the database connection.


Def some = Try {return 1} finally {return 2} does return 2, but this is not recommended by Scala.

Def some = Try {1} finally {2} returns 2, which is the recommended form of scala...

The best way to think of finally clses is as a way to ensure some side effect happens, such as closing an open file.

Finally is produced for side effects.


5 match expression

_, Wildcard, used as an option that cannot be determined.

Match applies more objects than Java switches. Java only applies to integer or enum types. Scala match can adapt to any constant.

Sth4match match {

Case some1 => // do something for some1

Case some2 => // do something for some2

Case _ => // do something for other condition


In addition, there is no break in the case of the match statement. This break is appended by default, after each alternative.

The last and most important difference is that each case has a return value. It is best not to let every case have side effects.


6 without beak and continue

The replacement of break and continue is to implement the requirement by recursion. If we traverse the array element, find the first element that does not start with-and ends with. Scala.

Def searchfrom (Index: int, argS: array [String]): Int =

If (index> = args. Length) Return-1 // The provided index has a problem.

Else if (ARGs (INDEX). startswith ("-") searchfrom (index + 1, argS) // if something goes wrong, continue to the next step, that is, implementing the continue

// Pay attention to the order in which the exclusion should be placed before the correct situation and filtered out.

Else if (ARGs (INDEX). endswith (". Scala") index // The value is found and returned to the caller of this method. The break function is implemented.

Else searchfrom (index + 1, argS) // if not found, continue to the next one. This statement must be executed at the end, that is, the while loop must continue.

// The return value must be specified for a recursive method. Otherwise, the compiler will not be able to know the returned value generated by calling the method in the method body.


7. Scope of the variable scope variable

It is basically the same as Java, but if a variable A is declared in Java, this a cannot be declared at will.

In Scala, variables with any name can be defined in a bracket. no matter whether the variable exists or not, you need to append a semicolon to the outside of the braces... I don't know what it means...


8. Reconstruct the script Encoding

A notable feature of script encoding is the introduction of VaR and the generation of side effects.

Remove VaR and only introduce the necessary Val.

Instead of providing the required information to the caller of the method.


A notable feature of functional programming is that there are many methods, but method functions are very specific.

Here is an example:

Print a multiplication table from 1 to 10. The Java method is a dual for loop.

Scala is also a dual for loop, but is allocated to two methods. For details, refer:

1 to 10 rows

2 1 to 10 columns

3. Ensure the format is not bad


Def makemultitable () = {

// A total of 10 rows of data. The makerow method is used to obtain each row of data.

Val tableseq = for (row <-1 to 10) yield makerow (ROW)

// Sort the obtained seq

Tableseq. mkstring ("\ n ")



// Each row of data is composed of each column of data, which is handed over to makerowseq for processing.

Def makerow (rowindex: INT) = makerowseq (rowindex). mkstring


// Process each vertex to obtain the data of the corresponding row.

Def makerowseq (rowindex: INT) =

For (COL <-1 to 10)



Val point = (row * col). tostring

Val Gap = "" * (4-point. length)

// Return Element

Gap + point



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: 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.