"Scala" singleton objects and associated objects

Source: Internet
Author: User

Scala single-Case objects

Scala cannot define static members, but instead defines singleton objects (singleton object). defined as the Object keyword.
An object defines a single instance of a class that contains the attributes you want:

object Accounts{    private var lastNumber = 0    def newUniqueNumber() = { lastNumber += 1; lastNumber}}

When you need a new unique account in your application, call Account.newuniquenumber ().
The constructor of the object is called when the object is used for the first time.

Scala Singleton objects can be used in the following scenarios:
-As a place to store tool functions or constants
-Efficiently share a single immutable instance
-When you need to use a single instance to coordinate a service

The difference between a class and a singleton object is that the singleton object has no arguments, and the class can . Because the Singleton object is not instantiated with the new keyword, there is no chance of passing it to the instantiated parameter. Each singleton object is implemented as an instance of the virtual class (synthetic class) and points to static variables because they have the same initialization semantics as the Java static class.

Standalone objects (standalone object)

A singleton object that does not share a name with the associated class is called an independent object. It can be used in many places, for example, as a tool class for related functional methods, or as an entry point for defining Scala apps.

Associated Objects (companion object)

When a singleton object shares the same name as a class, it is called a companion object of the Class (companion. The class and its associated objects must be defined in the same source file . The class is referred to as the associated Class (companion Class) for this singleton object. The class and its associated objects can access each other's private members .

class  account  { val  id = Account.newuniquenumber () private  var  balance = 0.0  def  deposit (amount:double) {balance + = Amount} ...} object  account  {  //companion object  private  var  lastnumber = 0  def  Newuniquenumbe R () = {Lastnumber + = 1 ; Lastnumber}}  

Note :
-The associated object of a class can be accessed, but not in scope. The account class must invoke the method of the associated object through Account.newuniquenumber ().
-In Repl, to define classes and objects at the same time, you must use Paste mode. Type :paste , and then type or paste the definition of the class and object, and the last Ctrl+d exit paste mode.

Using the associated object as a factory

We usually use the associated object as a factory.
Here's a simple example where you don't need to use ' new ' to create an instance.

class Bar(foo: String)object Bar {  defnew Bar(foo)}
Singleton object inheriting from class and trait

An object can extend a class and one or more attributes, and the result is an object that extends the class with the specified class and attributes, with all the attributes given in the object definition.

Examples of inheriting from abstract classes

A useful usage scenario for an extended class is to give a default object that can be shared. Consider, for example, a class that introduces a revocable action in a program:

Abstract  class undoableaction(val description:sting) {    defUndo (): UnitdefRedo (): Unit} Object donothingaction extends undoableaction("Do Nothing" ) {    Override defUndo () {}Override defRedo () {}}//Open and save features not yet implementedValAction = Map ("Open"Donothingaction,"Save"Donothingaction, ...)

The Donothingaction object can be shared by all places where this default behavior is required

Examples of mixed traits

Sometimes you can mix things like debugger or logging to build objects to help debug objects so that the object instance you build has a method like log:

trait  debugger  { def  log (message:string {//do something with message }}//no Debuggerval  child = new  Child //debugger added as the object is created  val  problemchild = new  problemchild with  Debugger  

reprint Please indicate the author Jason Ding and its provenance
Gitcafe Blog Home page (http://jasonding1354.gitcafe.io/)
GitHub Blog Home page (http://jasonding1354.github.io/)
CSDN Blog (http://blog.csdn.net/jasonding1354)
Jane Book homepage (http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)
Baidu Search jasonding1354 access to my blog homepage

"Scala" singleton objects and associated 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.