Scala companion classes and associated objects

Source: Internet
Author: User
Tags static class

When a singleton object has the same name as a class, this singleton object is referred to as the associated object of the class, and this class is called the companion class of the Singleton object.

The associated class and the associated object are to be defined in the same source file, and the associated object and the associated class can access each other's private members.

A singleton object that does not have the same name as the associated class is called an orphaned object.

Import Scala.collection.mutable.Map

Class Checksumaccumulator {

private var sum = 0

def add (b:byte) {

sum + = b

}

def checksum (): Int = ~ (Sum & 0xFF) + 1

}

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)

println ("s:" +s+ "CS:" +cs)

Cs

}

def main (args:array[string]) {

println ("Java 1:" +calculate ("Java"))

println ("Java 2:" +calculate ("Java"))

println ("Scala:" +calculate ("Scala"))

}

}

The Checksumaccumulator Singleton object has a method, calculate, that is used to calculate the checksum of the characters in the string parameter. It also has a private field, cache, and a mutable map that caches previously computed checksums. The first line of the 2 method, "if (Cache.contains (s))", checks the cache to see if the string passed in is already present as a key in the mapping. If it is, simply return the mapped value, "cache (s)". Otherwise, the ELSE clause is executed, and the checksum is computed. The first line of the Else clause defines a Val called ACC and initializes it with the newly created Checksumaccumulator instance. The next line is a for expression, looping through each character of the passed-in string, and calling ToByte on it to convert the character to Byte, and then pass it to the Add method of the Checksumaccumulator instance referred to by ACC. After the for expression is completed, the next line of the method is raised in ACC with checksum, obtaining the checksum of the incoming string, and depositing it in Val called CS. The next line, "cache + = (S-CS)", passes the string key mapped to the checksum value of the integer and adds the key-value pair to the cache map. The last expression of the method, "CS", guarantees the result of the checksum for this method.

The results are printed here:

S:java cs:-130

Java 1:-130

Java 2:-130

S:scala cs:-228

Scala:-228

The problem is, Checksumaccumulator Singleton object is not new, but there is a val acc = new Checksumaccumulator In the code, this is not a contradiction. In fact, here new is actually the associated class of the Checksumaccumulator singleton object, namely the Checksumaccumulator class, while the associated class and the associated object can access each other's private members, Therefore, ACC can access the cache variable of the Checksumaccumulator singleton object. Similarly, the first time the "Java" string is tested, the ACC instance executes the checksum () method, and then the data is stored in the cache Val. The second time the "Java" string is tested, the program fetches the data directly from the cache variable and returns it.

It can also be seen here that one difference between a class and a singleton object is that the singleton object is initialized at the first access, cannot be new, cannot take arguments, and the class can be new, with parameters. Each singleton object is implemented as a fictitious class that is pointed to by a static variable: an instance of the synthetic class, so they have the same initialization syntax as the Java static class.

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.