Programming in Scala notes-fourth chapters, classes and objects

Source: Internet
Author: User
Tags class definition csa

Similar to Java,scala, there is also the concept of classes and objects. I. Classes, properties, and methods

1. Class
A class is an abstraction of a kind of thing, and when a class is defined, it can be defined as a template that defines a series of objects of that class. For example, you have one of the following templates

Human: Having
  a name, having
  a brain,
  having limbs,
  having sex, being able to
  think, having a
  language ability;

The above template can be considered as a simple abstraction for normal human beings, then there are two people Zhang San and John Doe, which is the concrete example of human this template.

In Scala, a class is defined with the Class keyword, and an object of that class is instantiated with the new keyword. A simple class definition and instantiation is shown below

Class Checksumaccumulator {
  //specific definition code omitted
}

new Checksumaccumulator

Some of the properties and methods of the class can be written in the omitted part of the above code. The so-called attribute refers to some of the characteristics of the class, such as the name in the above example, gender, etc., can be regarded as a human property. The method refers to a number of logical fragments that the class can perform, such as the example above that defines the way in which humans walk in a standing walk, so that normal two human Zhang San and John Doe walk in a standing walk.
The properties and methods of the class are then analyzed.

2. Properties
Attributes can be defined using Var and val, such as
  

Class Checksumaccumulator {
  var sum = 0
}

Then, use the following code to new out two objects

Val acc = new Checksumaccumulator
val CSA = new Checksumaccumulator

Both ACC and CSA have a property sum. And the value is 0. As shown in the following illustration, the preceding two circles represent the specific storage of ACC and CSA objects, pointing to the same 0 because 0 is only one in the constant pool.
  
Execution acc.sum=3 can update the Sum property of ACC to 3, so now this is the case
  
  
As can be seen here, although ACC is defined in Val, it is possible to modify the value of the property. The function defined as Val is that if you point ACC to another Checksumaccumulator object, you will get an error. In general, it is best to define a property as private, a property of the private type, accessible and modified only by methods in that class, and try to avoid modifying the object's property values directly by external code. If a property change is required, it can be implemented by means of a method.

3. Methods
The method starts with Def and contains an executable code fragment. It is important to note that the parameter of the method is of type Val, and if you change the value of the parameter in the code, it will be an error.

Class Checksumaccumulator {
  private var sum = 0
  def add (b:byte): Unit = {
    sum + = b
  }
  def checksum (): Int = {
    return ~ (Sum & 0xFF) + 1
  }
}

The above code defines two methods, which can be simplified according to the definitions of the two methods.

Class Checksumaccumulator {
  private var sum = 0
  def add (b:byte): Unit = sum + = b
  def checksum (): Int = ~ (sum & 0xFF) + 1
}

As mentioned in the previous blog post, the return value is a unit statement that produces side effects. The side effects of the Add method here change the value of the sum variable. The impact of side effects either alters the value of a mutable variable, or produces some I/O, which does not affect the execution of other code.
For this method of returning a unit, you can remove the previous unit = section and wrap the function body in curly braces.

Class Checksumaccumulator {
  private var sum = 0
  def add (b:byte) {sum + = b}
  def checksum (): Int = ~ (Sum & ; 0xFF) + 1
}

The notation of the Add method in the above code, even if the return value of its execution logic is not a unit, is also shown to set the method return value to unit. Second, the sentence Division

Do not know if there is not found in the above code is not like Java code, the end of each line of code is separated by semicolons. In Scala, there is no need to write a semicolon at the end of each line of statements, and in general, line breaks as the default delimiter. Only when you write multiple lines of code in a row do you need to separate the code with semicolons.

val s = "Hello"; println (s)

Scala defaults to a direct delimiter for the behavior Code,

X
+ y

will be considered as two lines of code, x and + Y. But what if the same line of code needs to be wrapped. You can enclose the same sentence with parentheses, and you can use line breaks in parentheses.

(x
+ y)

is actually the line-break form of x + Y. Iii. Single-instance objects

Although Scala is a functional programming language, speaking of object-oriented, Scala is actually more rigorous than Java. In Java, a class can also have static properties or static methods, so that many of these static properties and methods can be used when no new object is added. But Scala does not have static properties and methods, and the use of any properties and methods is done through objects.
If you do need to call properties and methods in Scala directly using the class name, you should do so. Scala does this by providing a singleton object, or the companion object. Before we define a Checksumaccumulator class, we use another keyword, object, and the same name as Checksumaccumularot, which generates a companion object for the Checksumaccumulator class.

Import Scala.collection.mutable.Map
object Checksumaccumulator {
  private val cache = map[string, Int] ()
  def calculate (s:string): Int =
    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
  }
}

Next, we can use checksumaccumulator.calculate to calculate directly. Literally, it is the same as calling a static method in Java.
The Checksumaccumulator object above is called the companion object of the Checksumaccumulator class, and the Checksumaccumulator class is called the companion class of the Checksumaccumulator object. The associated object and the associated class, which need to be written in the same source file, and the associated class and the associated object can access each other's private members. Four, the code to run the entrance

In Java, a application is started with the method of public static void main (string[] args in a class). To run a Scala code, you need to define a singleton object and write a main method in the Singleton object that receives the parameter as an array of type string with the return value type unit.

Import Checksumaccumulator.calculate
object Summer {
  def main (args:array[string]) {for
    (arg <-args) C4/>PRINTLN (arg + ":" + Calculate (ARG))
  }
}

The main method in an object is the entrance to a application. Similar to the main method in Java.
  
But Scala also offers a trait called application, which can simply interpret trait as an interface in Java. If object inherits from the trait, then the main method is not required to run. Write the code that you originally wanted to write in the main method, directly in the curly braces that follow.

Import checksumaccumulator.calculate
Object Fallwinterspringsummer extends application {for
  (season <- List ("Fall", "Winter", "Spring"))
    println (season + ":" + Calculate (season))
}

This code is able to run, from the application can be seen, this has implemented a main method. The code written above is executed by the main construction method when the class is initialized.

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.