Scala Quick Learning Note (ii): Control structures, classes and objects

Source: Internet
Author: User

IV. Control Structure

1.if/else

In addition to the basic usage, the IF/ELSE statement can be used to assign values instead of ?: operators. This is because 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.

if Else x

2. Unlike the IF statement, the while statement itself has no value, that is, the result of the entire while statement is the unit type ().

The assignment statement in Ps:scala also has no value.

3. For statement used to iterate over a collection, in the formfor(item <- collection)。一些collection举例:

0 to list.length - 1
0 until list.length
val list = List("Tom", "Jach", "Jimmy", "Abby")

    • 嵌套for循环  直接分号隔开就行。
 for (i <-0 to 1; J <-1 to 2; k <-2 to 3) {    println ("i =%d, j =%d, K =%d". Format (i, J, K))  }
    • Conditional for loops such as the following code, I with conditions i % 2 == 0 , which means that only I that satisfies this condition will be executed by loop.
 for {i <-0 to 5     if i% 2 = =     0 <-1 to 2} {  println ("i =%d, J =%d". Format (i, j))}
    • Intermediate bound variables
Variable lower is introduced, 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.
Val list = list ("Html", "XML", "JSON", "text", "MD")for {ext <- list = Ext.tolowerc ASE if lower! = "html"} { println ("Accepted data format:" + Lower)}

Generates a new collection for (Claus) yield {body} that can be used to produce a new collection.

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

4.match

"Your selector" match {  case//handle Case 1     case  //  handle Case 2...    Case // handle the rest, like default in Switch-case}
    • Any type of constant or an expression with a constant result can be used for the match statement.
    • Each branch does not need to end with a break because Scala does not run through execution (fall through).
    • 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.
def passed_? (Grade:char) = {  grade match {    case True    // case ‘A‘ | ‘B‘ | ‘C‘ => true This is exactly what is happening in other languages, switch-case through execution Case    false  }}

5. Exceptions

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.

    • Throw exception: Throws an exception object with the Throw keyword. All exceptions are sub-types of throwable. 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.
    • Unlike Java code, the need to declare a method throws an exception, which saves the programmer a lot of trouble with theory.
      Def divide (X:int, y:int): Int = { ifthrownew Exception ("Divide by Zero") c7/>Else x/ y}
    • Catching Exceptions:
      • In Scala, the idea of pattern matching was borrowed to make an unusual match, so in the catch code, there was a series of case sentences.
      • 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.  

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.

6. Interrupt Loop:

    • There is no break or continue keyword in Scala. You can use the break method of the breaks class to implement the function of exiting the loop. Breakexception is an exception of type controlthrowable. In addition, your loop code needs to be surrounded by breakable, and Breakable's role is to catch the exception thrown by the break, so as not to affect your real product code.
       import  scala.util.control.breaks._ 
    • The idea of functional programming and avoid using break as much as possible. Functional programming is almost impossible without 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.
Val list = list ("Functions.md", "Menu.json", "index.html", "data.xml"= {  input match {      CaseFalsecase     x:: Sub = = {      ifreturnTrue       Else  hashtml (sub)  }}if(hashtml (list)) println ("There is At least one HTML file in the list ")else println (" There was no HTML file in the list ")

V. Classes and objects

1. The default access modifier is public.

Scala's classes have default basic constructors, and you can use new to create objects.

    • In a class definition, all statements that are not part of a method and a field are part of the primary constructor.

    • The parameters of the basic constructor are class parameters, class parameters (or default constructor parameters) The default access level is Object private, or Private[this] val, if you want to be able to use outside of the class, just show it as Val or Var, for example class ScoreCalculator(val athlete: String) .

    • Private constructors are placed in front of the class parameter list
classScorecalculator (athlete:string) {Privatevar total, count = 0println ("This was in the primary constructor") def report (Score:int) { Total+=Score Count+ = 1} def score=if(count = = 0) 0ElseTotal/count override def toString ()= athlete + "' s score is" +Score}val SC=NewScorecalculator ("Yao") println ("\njust created an object, now you can use it.\n") Sc.report (80) Sc.report (90) println (SC)
    • Auxiliary constructors: Constructors are identified with this. The primary constructor must be called first, or other constructors defined before it. This means that the primary constructor is the only way to create an object, regardless of which constructor you call.
classScorecalculator {var athlete= ""var degreeofdifficulty= 0.0def This(athlete:string) { This()//Call Primary constructor     This. Athlete =athlete} def This(athlete:string, degreeofdifficulty:double) { This(athlete)//Call another auxiliary constructor     This. degreeofdifficulty =degreeofdifficulty} override def toString= "Athlete:" + athlete + ", Degree of difficulty:" +Degreeofdifficulty}val SC1=NewScorecalculator ("Gao Min") Sc1.degreeofdifficulty= 3.7println (SC1) Val sc2=NewScorecalculator ("Fu Mingxia", 3.5) println (SC2)

2. Properties of the class

    • Scala's getter method formats such as name_= (parameters) , names, underscores, and equals signs are a whole and cannot have spaces between them.
    • The setter method must appear in pairs with the getter, that is, it cannot be read-only. Instead, getter can appear alone, meaning that read-only is possible.
    • Fields that are not declared as private are automatically generated by the Getter,setter method.

Not very understanding, and then study it.

3. Singleton object: Eliminate static. A singleton object can be divided into two types, one that does not share the source file and name with a class, called a standalone object (Standalone object), and, in contrast, shares the name with a class, called the companion object (Companion.

    • A standalone object is similar to a static class, and in a running environment there is only one object of this type, which is a natural implementation of the singleton design pattern that is instantiated by the runtime environment when it is first used. It is defined in a similar way to a class, except that the keyword is replaced with an object. Other aspects are similar to classes, such as inheriting other classes and traits. There is only one difference, and you cannot have a class parameter, that is, a constructor parameter.
    • If a singleton object has the same name as a class, and they are in the same source file, it is called the associated object of the class. It and the associated classes can access each other's private members.
    • The Apply method is a class-specific method of an object that can generally be used to create a companion class. The Apply method can be called in a concise manner, such asObject(args..)。

4. A standalone object can contain the main method and can be represented by the extends app (app trait).

extends App {  Args.foreach (println)}

Scala Quick Learning Note (ii): Control structures, classes and objects

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.