Scala Programming (ii) Classes and objects

Source: Internet
Author: User
Tags traits

Classes, fields, and methods

A class is the blueprint for an object. Once a class is defined, you can create objects from the class's blueprint with the keyword new, the definition of the class:

class checksumaccumulator {    //  class definition goeshere}

You can create objects:

New= [email protected]

In a class definition, you can place fields and methods, which are generically referred to as Members: member. Fields, either in Val or Var, are variables that point to the object. method, defined with Def, contains the executable code. A field retains the state or data of an object, and the method uses that data to work on the object. When instantiating a class, the execution period environment sets some memory to preserve the image of the state of the object-that is, the contents of the variable. For example, if you define the Checksumaccumulator class and give it a var field called sum:

class Checksumaccumulator {   = 0}

And instantiate two times:

New= [email protected]scalanew= [email protected]

The image of the object in memory might look like this:

Since the field sum defined in the class Checksumaccumulator is Var, not Val, it can be re-assigned to a different Int value:

scala> acc.sum = 3= 3

Now, the image will look like this:

Another argument for a field is an instance variable:instance variable, because each instance has its own set of variables. The variables of the object instance make up the memory image of the object. In this case, although ACC is Val, you can still change the object that the ACC points to. What you can't do with ACC is because it's Val, not Var, and you can't assign them to different objects again. For example, the following attempt will fail:

New checksumaccumulator<console>:12: Error:reassignment to Val       New  Checksumaccumulator           ^

ACC will always point to the same Checksumaccumulator object that is pointed at initialization, but the fields contained in the object can be changed at any time.

By turning a field into private: Private to block direct access to it can make the object robust:

class checksumaccumulator {   private var sum = 0 }

Sum is now private, so the only code that can access sum is defined in the class itself:

class checksumaccumulator {   private var sum = 0  = {     + =   b   } = {    return ~ (sum & 0xFF) + 1  }}

Any parameters passed to the method can be used inside the method. An important feature of the method parameters in Scala is that they are all Val, not var. If you want to reassign a parameter to a method, the result is a compilation failure:

Scala> def Add (b:byte): Unit = {     |   // compile however, because B is Val     |   sum + =     b| } <console>:11:error:value + = is not a member of         Byte/  compile but because B is Val           ^

The more concise style is to get rid of the return statement, and if no explicit return statement is found, the Scala method returns the last computed value in the method. If a method evaluates only a single result expression, you can remove the curly braces. If the result expression is short, you can even put it on the Def line:

class checksumaccumulator {  private var sum = 0  = sum + =  b= ~ (Sum & 0xFF) + 1}

A side effect is usually defined as changing the state or performing I/O activity somewhere outside the method. For example, in Add, the side effect is that sum is re-assigned. Another way to express this method is to remove the result type and equal sign, and place the method body in curly braces. In this form, the method looks like a process: procedure , a method that executes only for side effects:

class checksumaccumulator {  private var sum = 0  + = b  }= ~ (Sum & Amp 0xFF) + 1}

When you remove the equals sign in front of the method body, its result type is destined to be Unit. Whatever is included in the method body is no exception, because the Scala compiler can convert any type to Unit. That is, with curly braces but without an equal sign, it is essentially a way to explicitly define the result type as Unit:

Scala> def g () {"This String gets lost too"}g: () Unit

Therefore, if you need to return a value that is not a Unit, you must insert an equal sign:

scala> def h () = {"This String gets returned!" }h: () Stringscala> this String gets returned!

Semicolon Inference

In a Scala program, the semicolon at the end of the statement is usually optional. If there is only one statement in a line that can not be written, the semicolon is required if you write multiple statements in one line:

Scala> val s = "Hello"= Hello

If you want to enter a statement that spans multiple lines, most of the time just enter, Scala will separate the statements in the correct location:

if (x < 2)  println ("too small")else  println ("OK")

Occasionally Scala also divides sentences into two parts:

x+ y

This is divided into two statements x and + Y. If you want to use it as a statement x + y, you need to wrap it in parentheses:

(x+ y)

Or you can put + at the end of the line:

X ++z

In tandem with the infix operator like +, putting the operator at the end of the line rather than the costume is a popular Scala style.

The precise rule for a split statement is that the end of the line is considered a semicolon unless one of the following conditions is true:

1. A question line ends with a word that cannot be lawfully terminated as a statement, such as a period or infix operator.

2. The next line begins with a word that cannot begin as a statement.

3. Line ends in parentheses (...) or box [...] Internally, because these symbols cannot accommodate multiple statements.

Singleton Object

One aspect of

Scala's more object-oriented than Java is that Scala has no static members. The alternative is that Scala has Singleton objects: Singleton Object . In addition to replacing the class keyword with the object keyword, the definition of a singleton object looks like a class definition:

 //  file Checksumaccumulator.scala  Span style= "color: #0000ff;" >import   Scala.collection.mutable.Mapobject checksumaccumulator { private  val Cache = map[string, int] () def calculate (s:string): Int  = Span style= "color: #0000ff;" >if   (Cache.contains (s)) cache (s)  else
     {val acc  = new   Checksumaccumulator  for  (c <- s) Acc.add (C.tobyte) Val cs  = Acc.checksum () cache  + = (s-> CS) CS}}  

The singleton object in the table is called Checksumaccumulator, which is the same name as the previous example. When a singleton object shares the same name as a class, he is referred to as the associated objectof the class:companion object. the class and its associated objects must be defined in the same source file. The class is referred to as the associated classfor this Singleton object:companionclass. The class and its associated objects can access each other's private members.

The Checksumaccumulator Singleton object has a method calculate is used to calculate the checksum of the characters in the String parameter. One way to consider a singleton object is to use it as a static method of Java, invoking a method with a similar syntax: Singleton object name, point, method name:

Checksumaccumulator.calculate ("Every value is an object.")

A singleton object is not just a station for static methods. It is also an object of the first class, which can be regarded as a "signature" on an object by the name of the Singleton object:

Defining a Singleton object is not a definition type. If you just checksumaccumulator the definition of an object, you cannot build a variable of type Checksumaccumulator. It should be said that the Checksumaccumulator type is defined by the companion class of the Singleton object. However, singleton objects extend the superclass and can be mixed with traits. Since each singleton is an instance of the superclass and is mixed with a trait, you can call its methods by these types, refer to it with these types of variables, and pass it to the methods that require those types.

One difference between a class and a singleton object is that the singleton object has no arguments, and the class can. Because a singleton object cannot be instantiated with the new keyword, there is no chance of passing it arguments. Each singleton object is implemented as a fictitious classthat is directed to a static variable: an instance of thesynthetic class, so they have the same initialization syntax as the Java static class, and the singleton object is initialized the first time it is accessed.

Singleton objects that do not share names with the associated class are called orphaned objects:standaloneobject. It can be used for a number of reasons, including collecting related functional methods together, or defining an entry point for a Scala application.

Scala Program

To execute a Scala program, be sure to provide an orphaned singleton object name with the main method (with only one parameter, array[string], and the result type unit). Any singleton object that has a proper signature for the Main method can be used as the entry point for the program:

// file Summer.scala Import checksumaccumulator.calculateobject Summer {   for (Arg <- args)  + ":" +  Calculate (ARG))  }}

The name of the singleton object in the code is Summer. Its main method has a proper signature and can be used as a program. The first statement in the file is a reference to the Calculate method that defines the Checksumaccumulator object in the preceding precedent. This reference statement allows the simplified name of the method to be used in the section following the file. The main method body simply prints out the checksum for each parameter and parameter, separated by a colon.

Both Checksumaccumulator.scala and Summer.scala are not scripts, because they end with a definition. Conversely, the script must end with a result expression. So if you try to execute Summer.scala in a scripted manner, the Scala interpreter will say that Summer.scala is not ending with a result expression. The right thing to do is to actually compile the files with the Scala compiler and then execute the output class file. One way is to use the Scalac, Scala's basic compiler. Input:

?  Work  Scalac Checksumaccumulator.scala Summer.scala?  Work  lschecksumaccumulator$ $anonfun $calculate$1. class checksumaccumulator$. class Checksumaccumulator. class checksumaccumulator.scalasummer$ $anonfun $main$ 1.classsummer$. class Summer. class Summer.scala

This compiles the source file, but there may be a perceptible pause before the compilation is complete. The reason is that each time the compiler starts, it takes some time to scan the contents of the jar file and complete other initialization work even before the new source file is submitted for viewing. As a result, Scala's release package also includes a Scala compiler backend service called the FSC (Fast Scala compiler) :daemon. This can be used:

FSC Checksumaccumulator.scala Summer.scala

The first time the FSC is executed, a local server daemon is created that binds to the port on the computer. It then sends a list of files through the port to the background process to compile and the background process to complete the compilation. The next time the FSC is executed, the background process is already running, so the FSC will simply send the file list to the background process and it will start compiling the file immediately. With FSC, you only need to wait for the Java Runtime environment to start for the first time. If you want to stop the FSC daemon process, you can do fsc–shutdown to close it.

Regardless of whether the Scalac or FSC command is executed, the Java class file will be created, and the Scala command can then be run with the orphaned object name of the main method that contains the correct signature:

?  Work  -213-182

Application traits

Scala offers a feature, Scala. Application, you can save some finger input work:

Importextends  application {  for (season <-List ("Fall", "Winter", " Spring ")    +": "+ Calculate (season))}

The way to use this trait is to first write "extends application" after the name of the Singleton object. Then instead of the main method, you can put the code that you want to put in the main method directly between the curly braces of the singleton object, and then compile and run as you would for other programs.

This works because the trait application declares the main method with the appropriate signature and inherits it from the singleton object so that it can be used as a Scala program. The code between the braces is collected into the primary constructorof the Singleton object:Primary constructor, which is executed when the class is initialized.

Inheriting from application is shorter than writing an explicit main method, but it also has some drawbacks:

1. If you want to access command-line arguments, you cannot use it because the args array is inaccessible.

2. Because of the limitations of some JVM threading models, if the program is multithreaded, you need an explicit Main method.

3. Some implementations of the JVM do not optimize initialization code for objects executed by the application trait.

The application trait can therefore be inherited only when the program is relatively simple and single-threaded.

Scala Programming (ii) 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.