Scala---------Objects

Source: Internet
Author: User
Tags traits

Objects in Scala

Summary :

In this article, you'll learn when to use Scala's object syntax structure. You'll use it when you need a single instance of a class, or if you want to find a place to call for other values or functions . The main points of this article include:

1. Use the object as a singleton or as a storage tool method

2. Classes can have a companion object of the same name

3. Objects can extend classes or traits

4. The Apply method of an object is often used to construct a new instance of the associated class

5. If you do not want to explicitly define the main method, you can use an object that extends the app's characteristics

6. You can implement enumerations by extending the enumeration object

Single-instance objects

Scala does not have static or static fields , you can use the syntax structure of object to achieve the same purpose . An object defines a single instance of a class that contains the attributes you want. For example:

Object Accounts {

private Var lastnumber=0

def newuniquenumber () = {lastnumber+=1, lastnumber}

}

When you need a new unique account in your application, call Accounts.newuniquenumber (). The constructor of the object is called when the object is used for the first time. In this example, the accounts constructor is executed at the first Call of Accounts.newuniquenumber (). If an object is never used, its constructor is not executed.

An object can inherently have all the attributes of a class, and it can even extend other classes or traits. There is only one exception: you cannot supply constructor parameters. For any place where you use Singleton objects in Java or C + +, you can use objects in Scala:

As a place to store tool functions or constants

Effectively share a single immutable instance

When you need to reconcile a service with a single instance , you can refer to the singleton mode

Note: Many people look down on the singleton pattern. Scala offers tools that can make good designs and can make bad designs, and you need to make your own judgments.

Associated objects

In Java or C + +, you typically use classes that have both instance methods and static methods . In Scala, you can do the same with classes and "associated" objects with the same name as the class. For example:

Class Account {

Val Id=account.newuniquenumber ()

private Var balance =0

def deposit (amount:double) {Balance+=amount}

}

Object account{//companion objects

private Var lastnumber=0

Private Def newuniquenumber () = {Lastnumber+=1;lstnumber}

}

The class and its associated objects can access the private attribute to each other. They must exist in the same source file . This shows that the associated object of the class can be accessed, but not within the scope . For example, the account class must invoke the method of the associated object through account.newuniquenumber () rather than directly with Newuniquenumber ().

An object that extends a class or 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. A useful usage scenario is to give the default objects that can be shared. Consider, for example, a class that introduces a revocable action in a program:

Abstract class Undoableaction (Val description:string) {

Def undo (): Unit

def redo (): Unit

}

By default it can be "do nothing". Of course, we only need one instance for this behavior:

Object Donothingaction extends Undoableaction ("do nothing") {

Override Def undo () {}

Override Def redo () {}

}

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

Val Actions=map ("Open"-donothingaction, "save", donothingaction, ...)//Open and save feature not yet

Apply method

Apply Meaning

We usually define and use the Apply method of the object. The Apply method is called when an expression of the following form is encountered:

Object (parameter 1, ..., parameter n)

Typically, this-an apply method returns an object of the associated class . For example, the array object defines the Apply method, allowing us to create an array with an expression such as the following:

Array ("Mary", "had", "a", "little", "lamb")

Why not use a constructor? For nested expressions, it is much easier to omit the new keyword, for example:

Array (Array (1, 7), Array (2, 9))

Note: Array (100) and new Array (100) are easy to confuse. The previous expression called apply (100), outputting a array[int of element integer 100). The second expression calls the constructor, this (100), and the result is array[nothing], which contains 100 null elements.

Apply Example

Here is an example that defines the Apply method:

Class Account Private (Val id:int, initialbalance:double) {

private Var balance=initiaibalance

.........

}

Object Account {//Companion object

def apply (initialbalance:double) =

New Account (Newuniquenumber (), initialbalance)

}

This allows you to construct your account using the following code:

Val Acct = Account (1000.0)

Application objects

Main method

Each Scala program must start with the main method of an object, and the type of this method is array[string]=> Unit:

Object hello{

def main (args:array[string]) {

println ("Hello, world!")

}

}

Extend app Features

In addition to providing your own Main method each time, you can extend the app's characteristics and then put the program code in the Human constructor method body:

Object Hello extends app{

println ("Hello, world!")

}

Command-line arguments

If you need command-line arguments, you can get by using the args property :

Object Hello extends app{

if (Args.length > 0)

println ("Hello," +args (0))

Else

println ("Hello, world!")

}

Time traits

If you set the Scala.time option when invoking the application, the program exits with the elapsed time displayed

Scalac Hello.scala

Scala-dscala.time Hello Fred

Hello, Fred.

[Total 4ms]

All of this involves some little magic. The app trait extends from another trait delayedlnit, and the compiler has special treatment for that trait. All classes with this trait will be initialized to the Delayedlnit method. The main method of the app trait captures the command-line arguments, invokes the Delayedlnit method, and prints the elapsed time as required. In earlier versions of Scala there was a application trait to achieve the same goal. The trait is to perform program actions in the static initialization method and not be optimized by the instant compiler, so use the new app traits as much as possible.

Enumeration

Enumeration definition Initialization

Unlike Java or C + +, Scala does not have enumeration types. However, the standard class library provides a enumeration helper class that can be used to output enumerations. Defines an object that extends the enumeration class and initializes all the optional values in the enumeration with the value method invocation. For example:

Object Trafficlightcolor extends enumeration (

Val Red, Yellow,green=value

}

Here we define three fields: Red, yellow, and green, and then initialize them with the value call. This is shorthand for the following code:

Val Red = Value

Val Yellow = Value

Val Green = Value

Each call to the value method returns a new instance of the inner class, also called value. Alternatively, you can pass an ID, name, or two arguments to the value method:

Val Red = Value (0, "Stop")

Val Yellow = Value (10)//name called "Yellow"

Val Green = Value ("Go")//ID 11

If not specified, the ID is added one from the previous enumeration value, starting from zero, and the default name is called the field name.

Enumeration references

Once the definition is complete, you can use trafficlightcolor.red, Trafficlightcolor.yellow, and so on to refer to the enumeration values. If this becomes tedious, you can introduce the enumeration values directly using the following statement:

Import Trafficlightcolor._

It is important to note that the type of enumeration is Trafficlightcolor.value rather than Trafficlightcolor, which is the object that holds these values. It is recommended to add a type alias :

Object Trafficlightcolor extends Enumeration {

Trafficlightcolor = Value

Val Red, Yellow, Green=value

}

The enumerated type now becomes traffclightcolor.trafficlightcolor, but this only makes sense if you use the import statement. For example:

Import Trafficlightcolor._

def dowhat (color:trafficlightcolor) = {

if (color==red) "Stop"

else if (color==yellow) "Hurry Up"

Else "Go"

}

Access Enumeration

The ID of the enumeration value is returned by the ID method, and the name is returned by the ToString method. The call to Trafficlightcolor.values outputs the set of all enumerated values :

for (c <-trafficlightcolor.values)

println (c.id+ ":" +c)

Finally, you can find and locate by enumerating the IDs or names, and the following two pieces of code output the Trafficlightcolor.red object:

Trafficlightcolor (0)//will be called enumeration.apply

Trafficlightcolor.withname ("Red")




The source of this article http://www.cnblogs.com/sunddenly/p/4431647.html

Copyright NOTICE: Welcome reprint, Hope in your reprint at the same time, add the original address, thank you with

Scala---------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.