Scala Study Notes (1)

Source: Internet
Author: User
Tags traits

Preface

Scala is a language designed to implement scaleable language. Officially, it is called the hybrid language of object-oriented language and functional language. In addition, Scala can work with JavaProgramSeamless stitching, because Scala files are compiled into. class files and run on JVM. However, what I care more about is itsScaleable ). What is scalability for a language? What is the scalability of a language?

In my personal opinion, I think the scalability of the language may include two aspects:

1. Language scalability

2. scalability of programs written in this language

In Scala introduction, some developers can use Scala to define their own domain specific language. I think this may reflect the scalability of the scala language itself, that is, it has the potential to be processed as another language available in specialized fields (perhaps by adding some models, or some operations ).

For the second point, the most touching thing is the tuple to be seen right away. When I was working on a project, I wanted a function to return two more parameters, but I had to redefine a JavaBean (inheriting its predecessors to retain other previous return values), but this led to the upper layerCodeIn a mess, the original basebean is called, and the new bean is called later. It would be too convenient to have something similar to tuple in Java.

This article describes three parts:

Tuple-Different types of data can be stored in an array.

Singleton objects-Scala does not have static methods and attributes, all of which are replaced by singleton object (singleton object ).

Trait-Class interface in Scala, but it can have a method body, and can be mixed into the class during instantiation, without the need to generate a subclass to wrap a class

 

Tuples
Like lists, tuples are immutable, but unlike lists,Tuples can contain different types of elements.Thus whereas a list might be a list [int] or a list [String], a tuple cocould contain both an int and a string at the same time. tuples are very useful, for example, if you need to return multiple objects from a method. whereas in Java, you wowould often create a JavaBean-like class to hold the multiple return values, in Scala you can simply return a tuple.

 
Val pair = (99, "luftballons") Println (pair. _ 1) println (pair. _ 2)

Output:
99
Luftballons

Understand classes and Singleton objects

//In greetsimply. ScalaClassSimplegreeter {Val greeting= "Hello, world! "Def greet ()=Println (greeting)} Val g=NewSimplegreeterg. Greet ()

As in Java, classes in Scala encapsulate fields and Methods. fields are defined with eitherValOrVaR. Methods are definedDef.

Although classes in Scala are in every ways similar to Java, inSeveral ways they are quite different.

① One difference between Java and Scala involvesConstructors.

In Java, classes have constructors, which can take parameters, whereas in Scala, classes can take parameters directly. the Scala notation is more concise-class parameters can be used directly in the body of the class; there's no need to define fields and write assignments that copy constructor parameters into fields.

 
//In greetfancily. ScalaClassFancygreeter (GREETING: string) {def greet ()=Println (greeting)} Val g=NewFancygreeter ("Salutations, World") G. Greet

However, this write feature is that the greeting parameter is a constant and cannot be re-assigned within fancygreeter.

② Another area in which Scala departs from Java is thatYou can't have any static fields or methods in a Scala class.

Instead, scala allows you to createSingleton objectsUsing the keyword object.A singleton object cannot, and need not, be instantiated with new. it is essential automatically instantiated the first time it is used, and as the "Singleton" in its name implies, there is ever only one instance. A singleton object can share the same name with a class, and when it does, the Singleton is called the class's companion object. the Scala compiler transforms the fields and methods of a singleton object to static fields and methods of the resulting binary Java class.

//In worldlygreeter. Scala//The worldlygreeter classClassWorldlygreeter (GREETING: string) {def greet ()={Val worldlygreeting=Worldlygreeter. worldify (greeting) println (worldlygreeting )}}//The worldlygreeter companion objectObject worldlygreeter {def worldify (S: string)= S + ", world! "}

If there is no corresponding class but only one object, it is called stand-alone. object.

//In worldlyapp. Scala//A singleton object with a main method that allows//This singleton object to be run as an applicationObject worldlyapp {def main (ARGs: array [String]) {Val WG=NewWorldlygreeter ("hello") WG. Greet ()}}

A singleton object is either a companion or a stand-alone object.

③ A Java file must be named as a class in the file, but Scala does not.

However, the editor still wants to use the class name Scala file name, because it makes it easier for other programmers to find the desired file.
Therefore, scala files are divided into two types: class and script. Class files cannot be run directly, but scripts can. The script statement must end with an execution statement.

Scala worldlygreeter. Scala # This won't work!

The worldlygreeter. Scala file must be driven by the worldlyapp. Scala file. Therefore, the two files must be compiled together. You can use the scalac command to complete this task:

Scalac Worldlyapp. Scala worldlygreeter. Scala

Each time the scalac command is executed, a JVM instance is generated. JVM has a noticeable latency at startup, so you can consider usingFSCCommand to replace the scalac command. When the FSC command is executed for the first time, it generates a daemon and binds the process to a port number on the local machine. All files to be compiled will be sent to the daemon through this port number. This process will not stop until you use the commandFSC-ShutdownStop manually. In this way, except for the first time there will be latency, other times will immediately compile the given file without the need to start JVM again.

 
Understand traits and mixins

Trait is a bit similar to interfaces in Java, but there are also differences.
① Java interfaces only define the method name and parameter list, and the method body cannot be defined. Trait can define the method body.
For example

Trait friendly {def greet ()= "Hi"}

② Implement is used to implement interfaces in Java, while extends is used to implement trait in Scala.

Scala no longer has the keyword implement. Similarly, the class in Scala can inherit up to 0 traits.

 
ClassDogExtendsFriendly {override def greet ()= "Woof"}

Note that, unlike Java, you must specify the override keyword to override a method in Scala. If the override keyword is not added during method rewriting, scala compilation will fail.

③ The biggest difference between Java interface and Scala trait is that Scala can be mixed into a trait when a class is instantiated.

 Trait friendly {def greet () = "Hi" }  Class DogExtends  Friendly {override def greet () = "Woof" }  Class Hungrydog Extends  Dog {override def greet () = "I 'd like to eat my own dog food" } Trait exclamatorygreeter  Extends  Friendly {override def greet () = Super . Greet () + "! " } Var pet: friendly = New Douplintln (pet. Greet () pet = New  Hungrydouplintln (pet. Greet () pet = New  Dog With exclamatorygreeterprintln (pet. Greet () pet = New  Hungrydog with exclamatorygreeterprintln (pet. Greet ()) 

Output:
Woof
I 'd like to eat my own dog food
Woof!
I 'd like to eat my own dog food!

What are the benefits of doing so?

In the past, if you wanted to output the "I 'd like to eat my own dog food" output in the hungrydog class, it would be "I 'd like to eat my own dog food !", Then we need to add a subclass, rewrite its method, and add it to the output string !, In trait, you only need to "with" a trait when the hungrydog class is instantiated to achieve the packaging effect.

Therefore, the With keyword can be used to implement the functionality of the package.

 

Reference:

First step to Scala

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.