[Scala Basic series 05] Scala control structure

Source: Internet
Author: User
Tags case statement

1.If statements

Scala's If statement can complete the IF statement in other languages, at the same time, if/else usually has values that can be used to assign values, or instead of the ternary conditional operator (?:). However, it can be more powerful than the conditional operator because you can write very complex blocks in If-else.

1.1. Common IF statements
 package   com.tv189.foundation  Span style= "color: #008000;" >/**   * Created by Molyeo on 2015/7/30.  */ object ifcondition {def main (args:array[string]) {val checkPoint  = 80 def check (current:int): Unit  = { if
     (current >= CheckPoint) {println (" Success ")}  else   {println ( "Fail" 
    
     )}} check (
     80) Check ( 90) Chec K ( 30 
1.2. Assigning values with an if statement

The If/else statement can be used to assign values instead of ?: operators, thanks to an important feature of Scala, in Scala, each statement block has a value, which is the value of the last statement in the statement block. Take a look at the following code.

def printabs (x:int) {  ifelse  x  println ("The Abs of%d is%d"   Ifelse  xprintabs (-5) println (ABS (-6))

In the first function printabs, an if-else statement is used to assign the ABS value, which acts as a C or Java ?: operator. Further, because the value of the last statement of the statement block is the value of the entire block, the statement block has only one statement when the curly brace {} can be omitted. Therefore, the function of absolute value can be abbreviated to only one row.

2.While statements

Scala's while statement is similar to the while statement in other languages, and experienced programmers can skip this section. Unlike the IF statement, the while statement itself has no value. Alternatively, the result of the entire while statement is the unit type ().

2.1.while Cycle

As with most languages, the while loop in Scala includes both the loop body and the loop condition, and the loop experience continues as the loop condition is met.

 Packagecom.tv189.foundation/*** Created by Molyeo on 2015/7/30.*/Object Whileconditionextendsapp{def reverse (number:int)={var result= 0; var temp=Number ;  while(Temp! = 0) {result= Ten * result + temp% 10; Temp/= 10;    } result; } println ("The result of reverse (12345) is" +reverse (12345) def sum (input:int)={var total= 10; var temp=input;  while(Temp > 0) { Total= temp +Total ; Temp= Temp-1;    } total; } println ("The result of sum (Ten) is" +sum (10));}

Run results

The result of reverse (12345) is 54321 theresult of sum (Ten) is 65
2.2.do-while Cycle

The difference between the Do-while loop and the while loop is that the Do-while loop executes the loop body before judging the condition, which means that the loop body will be executed at least once.

Val i = 0 do {  println ("executed once"while (i! = 0)

Please note
In Scala, an assignment statement has no value, unlike C and Java, so it's not possible to write in Scala, which is common in other languages while((c = getchar()) != ‘\n‘) . This is because, in Scala, c = getchar() although C is assigned a value, the value is not assigned to the entire statement. This is different from other languages, in C and Java, the value of C is also assigned to the entire statement.

3.For statements

Scala's for statement is very different from other languages, and even experienced programmers need to know this part of the text carefully.

In Scala, there is no for (initialize; test; update) for loop, and to implement related functions, either use the while instead, or use the Scala for statement for (i <- 1 to n) .

3.1. Iteration 3.1.1 for collections. Basic syntax

A for statement that iterates over a collection, in the form of a for(item <- collection) bit like Java for (type var : arr) , or C # foreach(type var in arr) .

Since there are many ways to create a collection in Scala, the for statement is relatively flexible, see the example below.

 Packagecom.tv189.foundation/*** Created by Molyeo on 2015/7/30.*/Object Forconditionextendsapp{val List=list ("One", "I", "three", "four"); println ("-------------Use to-------------")   for(I<-0 to List.length-1) {print ("  "+list (i));  } println (); println ("-------------use until-------------")   for(i<-0until List.length) {Print ("  "+list (i));  } println (); println ("-------------use until-------------")   for(item<-list) {Print ("  "+item)}}

Please note
Please note that the above code to and until differences, to contains the upper boundary, until is not included.

3.1.2. Nesting for loops

In Scala, nesting for loops is easier than other languages, as long as the expressions are placed in the parentheses of the for, separated by semicolons (;). Like what:

 for (i <-0 to 1; J <-1 to 2; k <-2 to 3) {    println ("i =%d, j =%d, K =%d". Format (i, J, K))  }

The above code is a nesting of i,j,k three loops.

3.1.3. Conditional for Loop

The loop for A for loop can also have conditional statements that filter the items in the loop. Like what:

 for {i <-0 to 5     if i% 2 = =     0 <-1 to 2} {  println ("i =%d, J =%d". Format (i, j))}

In the above code, I is conditional i % 2 == 0 , which means that only I that satisfies this condition will be executed in a loop.

3.2. Intermediate bound variables

Take a look at the following example.

Val list = list ("Html", "XML", "JSON", "text", "MD")for {ext <- list     = Ext.tolowerc ASE     if lower! = "html"} {  println ("Accepted data format:" + Lower)}

You may have discovered that in the code above, toLowerCase may execute two times in a loop. We hope to avoid this situation. Scala does provide a way for you to introduce a variable halfway through the For statement and then use it in the loop body.

In the above code, we introduced the variable lower, which is less val than the way we usually define variables. This variable can be used in both the for expression and in the loop body.

3.3. Used to generate a new collection

The For statement, with yield, can be used to produce a new collection. This is shown in the following example.

Val result =  for (I <-1 to 3; J <-2 to 4)  yield {    + J  }println (Result)

The above code produces a set of vectors (3, 4, 5, 4, 5, 6, 5, 6, 7).

Please note
The format of the For-yield is for (Claus) yield {body}, and the yield cannot be placed in curly braces.

4. Basic Match Statement

Scala's match statement functionality is basically similar to switch-case in other languages, but much more powerful. In this section we only introduce the basic syntax, and the "Strong" section is reserved for pattern matching.

Programmers who have used the Switch-case statement know that it is useful to have you choose a branch to execute in a series of options. Mach is similar, but still slightly different.

"Your selector" match {  case//handle Case 1     case  //  handle Case 2...    Case // handle the rest, like default in Switch-case}

In addition to the syntax differences above, match and switch statements are like different points.

    1. Any type of constant or an expression with a constant result can be used for the match statement. Switch in many languages allows only the base type, while Java is stricter, allowing only shaping and enumeration types.
    2. Each branch does not need to end with a break because Scala does not run through execution (fall through).
    3. As with the if expression, the match expression has the result as well. It is also understandable that match is actually another way of writing the if of multiple branches.

Let's look at a practical example.

DEF score (Grade:char) ={grade Match { Case' A ' = println ("85~100")     Case' B ' = println ("70~84")     Case' C ' = println ("60~69")     Case' D ' = println ("45~60")     Case' E ' = println ("<45")     Case_ = = println ("Input error")}}def Passed_? (Grade:char) ={grade Match { Case' A ' | ' B ' | ' C ' =true     Case_ =false}}score (B)if(Passed_?) (' B ')) println ("congrats!")Elseprintln ("uh~ Oh, we are sorry ...")

The function score contains a regular match statement, where we can see that each branch executes only the code of this branch, not through. Finally, there is a case _ case that is not listed. Scala Underline (_) is often used as a wildcard character.

There are two places to pay attention to the function passed_. One is the return type of this function is Boolean, because the function body has only one match statement, it is obvious that its return value is the match statement value. The value of the match statement whose type is the common type of each branch. If these types are different, take the nearest common parent class.

Another notable point is that case ‘A‘ | ‘B‘ | ‘C‘ => true this is precisely the case in other languages where switch-case runs through execution, similar to

 Case ' A ' : case ' B ' :casereturntrue;

This also explains from one side that Scala, canceling break and Fall-through, can make the code more concise, semantically clearer, and not easy for programmers to make mistakes.

5. Exception Handling

Scala's exception handling is the same as in other languages, with the same functionality, with only subtle differences in syntax. The exception mechanism appears in order to deal with the abnormal situation in the program, such as the file to be found does not exist, the database is not connected, network interruption and so on. When an exception is encountered, the method throws an exception, terminates the execution of the method itself, passes the exception to its caller, the caller can handle the exception, or it can be upgraded to its caller. The runtime will continue to escalate the exception until a caller can handle it. If it has not been processed, the entire program is terminated.

5.1. Throwing Exceptions

The exception in Scala is thrown in the same way as Java, throwing an exception object with the Throw keyword. All exceptions are throwable subtypes, which is the same as in Java. In fact, Scala's Throwable is Java.lang.Throwable's nickname.

As explained in the bottom type nothing, the throw expression is of type, or nothing, because nothing is a subtype of all types, so the throw expression can be used where the type is needed.

Def divide (X:int, y:int): Int = {  ifthrownew Exception ("Divide by Zero") c6/>Else x/ y}

The return type of the above code divide method is int, because throw new Exception("Divide by zero") the type is nothing and is a subclass of int, so the above code is correct.

5.2. Catching exceptions

The mechanism of exception snapping is the same as in other languages, if an exception occurs, the catch sentence is captured sequentially. Therefore, in the catch sentence, the more specific the exception is to rely on the front, the more common the more the anomaly. If the exception thrown is not in the catch phrase, the exception is not processed and is escalated to the caller.

Catch clauses that catch exceptions, which are not the same syntax as in other languages. In Scala, the idea of pattern matching is borrowed to make an unusual match, so in the catch code, there is a series of case phrases, as shown in the following example.

Importjava.io._Importjava.lang.SecurityExceptionTry{val file=NewFile ("MyFile") Val Stream=Newfileinputstream (file)//Use the stream}Catch {   CaseEx:filenotfoundexception = println ("File not Found")   CaseEx:securityexception = println ("You don't have read access to the file")   Case_: Throwable = println ("Other exception happened")}

The content in the catch sentence is exactly the same as the case in match. Because exception snapping is in order, if the most common exception, Throwable, is written at the front, then the case behind it is not captured, so it needs to be written in the last face.

5.3.finally words

The finally sentence is used to perform the steps that need to be performed, whether normal or an exception occurs, and is typically used for object cleanup. As shown in the pseudo code below, Scala's finally is the same as the other languages.

Val file = getFiletry  {  //Use thefile}catch  {   // Handle Exception }finally  {  //Close the file no matter how above code goes}
Interrupt loop

There is no break or continue keyword in Scala, which means that Scala does not encourage using break or continue to jump out of a loop. However, if you really want to use it, Scala provides the appropriate classes and methods.

Use break

If necessary, you can use the break method of the breaks class to implement the function of exiting the loop. This is shown in the following example.

 import   Scala.util.control.breaks._val List  = List ("Functions.md", "Menu.json", "index.html", "Data.xml" ) var found  = false  breakable { for  (item <- list) { if  (      Item.endswith ("HTML"  = true  break   if   ( Found) println ( there is at least one HTML file in the list ""  else   println (" There is no HTML file in the list ") 

Code like this, we often see in instruction programming, such as the Java,c language. But there is still a difference in the actual implementation. Scala's break is a method of the breaks class, so the above code first introduces the breaks class.

Import Scala.util.control.breaks._

In addition, break is actually implemented by throwing an exception, and the source code is

 Break throw Breakexception}

Here, Breakexception is an exception of type controlthrowable. Therefore, your code needs to be surrounded by breakable. Breakable's role is to catch the exception thrown by break, so as not to affect your real product code. Its source code is similar to

Def breakable (op: = = Unit)    {try  {    opcatch  {        Case Ex:breakcontrol =        ifthrow  ex    }  }

The use of break in Scala is really inconvenient, continue, then there is no, so, I'd better not use it. This is exactly what Scala's designers are looking for, avoiding the use of break and continue.

Avoid using break and continue

Avoiding the use of break and continue is completely achievable. A simpler and more consistent approach to our programming habits is to use the while loop to put the terminating condition in the while sentence, such as the example above, to be modified, you can put found in the while clause.

false  while (! found) {  for item <- List}    {if(Item.endswith ("HTML")) {         True    }}  }

That's a viable approach, but it's not what Scala designers want to see. What they want to see is the idea that programmers can have functional programming. Or take the above example, from the point of view of the function, the above function, with a function to express, is in a string list to find the end of the HTML string, this function can be defined as the following hashtml.

 val list = list ("Functions.md", "Menu.json", "index.html", "Data.xml" ) def hashtml ( Input:list[string]): Boolean  = case  Nil = false  case  x:: Sub = > if  (X.endswith (" HTML ") return  true  else   hashtml (sub)}}}  if  (hashtml (list)) println ("There is at least one HTML F Ile in the list ")  
Hashtml is easier to understand if the list contains no elements, of course false, and then the list as two parts, the first element, and the remaining sub-list. If the first element is HTML, it is already found, and if it is not, it continues to look in the sub-list. This way of thinking is more easy to understand and communicate. In the sub-list lookup, and the original problem is the same, but the input set is shrinking, this is a typical recursive problem. In fact, functional programming is almost inseparable from recursion. More specifically, the above hashtml is a tail recursion, most functional language compilers are optimized for tail recursion, and Scala is no exception. For programmers, there is no need to worry about the performance degradation of using tail recursion. For tail recursion, subsequent articles are discussed.

From the instruction-type thinking to the function, it takes time, not forcing the moment to complete. But from now on, we can slowly realize the elegance of functional programming.

Reference documents:

Http://meetfp.com/zh/scala-basic/break

[Scala Basic series 05] Scala control structure

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.