Scala Basics Tutorial (i): Introduction, environmental Installation _scala

Source: Internet
Author: User
Tags mixed reserved

Scala basic syntax

If you have a good understanding of the Java language, it will be easy to learn Scala. The most important difference between Scala and Java is that the line terminator is optional. Consider a Scala program that can be defined as a collection of objects that communicate by calling each other's methods. Now, briefly look at what is called Class, Object, method, and temporary variable.

· Object-object has state and behavior. For example: A dog has a state-color, name, breed, it has behavior-swings, barks, eats things. An object is an instance of a class.

· Class-class can be defined as a template/blueprint to describe the behavior/indicate its type support object.

· Method-The method is essentially an act. A class can contain many methods. It is in the logical write method, the data is manipulated and all actions are executed.

· Fields-Each object has a unique set of temporary variables, which is called a field. The state of the object is created by the values assigned to those fields. First Scala Program: Interactive mode Programming:

Call interpretation does not pass a script file as a parameter displays the following prompt:

C:>scala
Welcome to Scala version 2.9.0.1
Type in expressions to have them evaluated.
Type:help for more information.
Scala>

Type a scala prompt for the following text, and then press ENTER:

Scala> println ("Hello, scala!");

This will produce the following results:

Hello, scala!.
Script Mode Programming:

Let's look at a simple code that prints a simple sentence: Hello, world!

Object HelloWorld {
* This'll print ' Hello world ' as the output
*/
def main (args:array[string]) {
println ("Hello, world!")//prints Hello World
}
}

Let's take a look at how to save the file, compile and run the program. Please follow the steps below:

1. Open Notepad and add the above code.

2. Save the file as: Helloworld.scala.

3. Open the Command Prompt window and go to the directory where you saved the program files. Let's say it's c:>.

4. Type "Scalac Helloworld.scala" and then press ENTER to compile the code. If there are no errors in the code, the command prompt automatically wraps to the next line.

5. The command above will generate several class files in the current directory. One of the names is called Helloworld.class. This is a byte code that can be run in the Java Virtual Machine (JVM).

6. Now, type "Scala HelloWorld" to run the program.

7. You can see "Hello, world!" Print on the window.

C:> Scalac Helloworld.scala
C:> Scala HelloWorld
Hello, world!.
Basic syntax

Regarding the Scala program, this is very important to note the following points.

· Case-sensitive-Scala is case-sensitive, which means that identifying hello and hello can have different meanings in Scala.

· Class name-capitalize the first letter of all class names.

If you need to use several words to form the name of a class, capitalize the first letter of each word.

Example: Classmyfirstscalaclass

· Method name-The first letter of all method names is in lowercase.

If several words are used to form the name of the method, the first letter of each word should be capitalized.

Example: Defmymethodname ()

· program file name-the name of the program file should exactly match the name of the object.

When you save a file, you should save the object name it uses (remember Scala is case-sensitive) and append ". Scala" to the file extension. (if the filename and object name do not match, the program will not compile).

Example: Suppose "HelloWorld" is the name of an object. Then the file should be saved as ' Helloworld.scala '

· def main (args:array[string])-The Scala program starts with the main () method, which is the mandatory entry section of each Scala program. Scala modifier:

All Scala components require a name. Using objects, classes, variables, and method names is called an identifier. Keywords cannot be used as identifiers and identities to be case-sensitive. Scala supports the following four types of identifiers: literal identifiers

Alphanumeric identifiers begin with letters or underscores, and can use letters, numbers, or underscores. The "$" character is reserved in Scala and the identifier is not available. The following are valid letter identifiers:

Age, salary, _value, __1_value

The following are illegal identifiers:

$salary, 123ABC,-salary
operator identification

The operator identifier is one or more operator characters. Action characters are printable ASCII characters, such as +,:,?, ~ or #. The following are the legal operator identities:

+ + +::: <?>:>

The Scala compiler will make them a valid Java identifier and embed the $ character in the internal "rolling" operator identifier. For example, the identifier:-> represents an internal representation of $colon$minus$greater. Mixed identifiers

A mixed identifier consists of an alphanumeric qualifier followed by an underscore and operator identification. The following are valid mixed identifiers:

unary_+, myvar_=

Here, as a method name unary_+ defines a unary + operator and myvar_= used to define an assignment operator as a method name. Immediate number identifier

A text ID is any string contained in an inverted quotation mark (' ... '). The following are legal text IDs:

' x ' <clinit> ' yield '
Scala keywords:

The following list shows the reserved words in Scala. These reserved keywords may not be used as constants or variables, or any other identifier name.

Abstract

Case

Catch

Class

Def

Todo

Else

Extends

False

Final

Finally

For

Forsome

If

Implicit

Import

Lazy

Match

New

Null

Object

Override

Package

Private

Protected

Return

Sealed

Super

This

Throw

Trait

Try

True

Type

Val

Var

While

With

Yield

-

:

=

=>

<-

(a):

<%

":"

#

@

Notes in Scala

Scala supports Single-line and multiline annotations that are very similar to Java. Multiple-line annotations can be nested, but must be nested correctly. Any comments and any characters that are available will be ignored by the Scala compiler.

Object HelloWorld {
* This'll print ' Hello world ' as the output
* This is a example of multi-line comments.
*/
def main (args:array[string]) {
Prints Hello World
This is also a example of single line comment.
}
}
Blank Lines and spaces:

Contains only spaces, may have comment lines, is called a blank line, and Scala will completely ignore it. Tags can be separated by spaces and/or annotations. Line feed:

Scala is a line-oriented language, and statements can end with semicolons (;) or line breaks. Semicolons are usually optional at the end of a declaration. You can type a desired if the statement appears itself on one line. On the other hand, it is necessary to write semicolons on one line of multiple statements:

val s = "Hello"; println (s)
Scala Package:

A package is a code-named module. For example, the Lift utility pack net.liftweb.util. The package declaration is the first non comment line in the source file, as follows:

Package Com.liftcode.stuff

Scala's packages can be imported so that they can be referenced within the current compilation scope. The following statement is the contents of the Import Scala.xml package:

Import Scala.xml._

You can import encapsulated classes and objects, for example, import HashMap from scala.collection.mutable:

Import Scala.collection.mutable.HashMap

You can import multiple classes or objects from a single encapsulated scala.collection.immutable package, for example, TreeMap and TreeSet:

Import scala.collection.immutable. {TreeMap, TreeSet}

The Scala language can be installed on any UNIX or Windows-like system. To install Scala, you must first install Java1.5 or later to install on your computer. To install Scala on Windows: Step (1): Java settings:

First, you must set the JAVA_HOME environment variable and add the JDK's Bin directory to the path variable. To verify that you can work, at the command prompt, type: java-version, and then press ENTER. You should see something similar to the following:

C:>java-version
Java Version "1.6.0_15"
Java (TM) SE Runtime Environment (build 1.6.0_15-b03)
Java HotSpot (TM) 64-bit Server VM (build 14.1-b02, Mixed mode)
C:>

Next, test to see if the Java compiler is installed. Enter Javac-version. You should see something similar to the following:

C:>javac-version
Javac 1.6.0_15
C:>
Step (2): Scala settings:

Next you can download Scala from the following URL http://www.scala-lang.org/downloads. While writing this tutorial, download the Scala-2.9.0.1-installer.jar and put it in the c:/> directory. Make sure that you have administrator privileges. Now type the following command at the command prompt:

C:>java-jar Scala-2.9.0.1-installer.jar
C:>

The above command displays an installation wizard that will be booted to install on a Windows computer. During the installation process, it asks for the license agreement, accepts it, and further asks Scala where it will be installed. Select the default given path C:programfilesscala, you can select a suitable path. Finally, open a new command prompt, type scala-version, and then press ENTER. You should see the following:

C:>scala-version
Scala Code Runner version 2.9.0.1--Copyright 2002-2011, LAMP/EPFL
C:>

Congratulations have been installed Scala on the Windows machine. The next section shows how to install Scala on Mac OS X and Unix/linux machines. Install Scala steps on Mac OS X and Linux (1): Java settings:

Make sure that you have Java JDK1.5 or later installed and set the JAVA_HOME environment variable on your computer, and that the JDK's Bin directory is added to the path variable. To verify that the installation is correct, at the command prompt, type java-version, and then press ENTER. You should see something similar to the following:

$java-version
Java Version "1.5.0_22"
Java (TM) 2 Runtime environment, Standard Edition (build 1.5.0_22-b03)
Java HotSpot (TM) Server VM (build 1.5.0_22-b03, Mixed mode)
$

Next, test to see the installed Java compiler. Enter Javac-version. You should see something similar to the following:

$javac-version
Javac 1.5.0_22
Javac:no Source Files
Usage:javac <options> <source files>
................................................
$
Step (2): Scala settings:

Next you can download Scala from the following URL http://www.scala-lang.org/downloads. While writing this tutorial, download the Scala-2.9.0.1-installer.jar and put it in the/tmp directory. Make sure you have administrator privileges to operate. Now, at the command prompt, type the following command to execute:

$java-jar Scala-2.9.0.1-installer.jar
Welcome to the installation of Scala 2.9.0.1!
The homepage is at:http://scala-lang.org/
Press 1 to continue, 2 to quit, 3 to redisplay
1
................................................
[Starting to unpack]
[Processing Package:software package installation (1/1)]
[Unpacking finished]
[Console installation Done]
$

During the installation, it asks the license agreement, accepts it to type 1, and it asks where Scala is installed. Here is the directory/usr/local/share, you can choose a suitable path. Finally, open a new command prompt, type Scala's-version, and then press ENTER. You should see the following:

$scala-version
Scala Code Runner version 2.9.0.1--Copyright 2002-2011, LAMP/EPFL
$

Congratulations, Scala has been installed on the Unix/linux machine.

If you have a good understanding of the Java language, it will be easy to learn Scala. The most important difference between Scala and Java is that the line terminator is optional. Consider a Scala program that can be defined as a collection of objects that communicate by calling each other's methods. Now, briefly look at what is called Class, Object, method, and temporary variable.

· Object-object has state and behavior. For example: A dog has a state-color, name, breed, it has behavior-swings, barks, eats things. An object is an instance of a class.

· Class-class can be defined as a template/blueprint to describe the behavior/indicate its type support object.

· Method-The method is essentially an act. A class can contain many methods. It is in the logical write method, the data is manipulated and all actions are executed.

· Fields-Each object has a unique set of temporary variables, which is called a field. The state of the object is created by the values assigned to those fields. First Scala Program: Interactive mode Programming:

Call interpretation does not pass a script file as a parameter displays the following prompt:

C:>scala
Welcome to Scala version 2.9.0.1
Type in expressions to have them evaluated.
Type:help for more information.
Scala>

Type a scala prompt for the following text, and then press ENTER:

Scala> println ("Hello, scala!");

This will produce the following results:

Hello, scala!.
Script Mode Programming:

Let's look at a simple code that prints a simple sentence: Hello, world!

Object HelloWorld {
* This'll print ' Hello world ' as the output
*/
def main (args:array[string]) {
println ("Hello, world!")//prints Hello World
}
}

Let's take a look at how to save the file, compile and run the program. Please follow the steps below:

1. Open Notepad and add the above code.

2. Save the file as: Helloworld.scala.

3. Open the Command Prompt window and go to the directory where you saved the program files. Let's say it's c:>.

4. Type "Scalac Helloworld.scala" and then press ENTER to compile the code. If there are no errors in the code, the command prompt automatically wraps to the next line.

5. The command above will generate several class files in the current directory. One of the names is called Helloworld.class. This is a byte code that can be run in the Java Virtual Machine (JVM).

6. Now, type "Scala HelloWorld" to run the program.

7. You can see "Hello, world!" Print on the window.

C:> Scalac Helloworld.scala
C:> Scala HelloWorld
Hello, world!

. From:http://www.yiibai.com/scala/scala_basic_syntax.html

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.