Scala Basics Tutorial (ii): Data type, variable _scala

Source: Internet
Author: User
Tags mixed modifier reserved
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}

Scala's data types are all the same in Java, with the same memory footprint and precision. The following table is about the details of all the data types available in Scala:

Data type

Describe

Byte

A 8-bit signed value. range from-128 to 127

Short

A 16-bit signed value. range from-32768 to 32767

Int

A 32-bit signed value. range from -2147483648 to 2147483647

Long

A 64-bit signed value. From-9223372036854775808 to 9223372036854775807

Float

32-bit IEEE754 single-precision floating-point number

Double

64-bit IEEE754 double-precision floating-point number

Char

16-bit unsigned Unicode character. range from u+0000 to U+FFFF

String

Character sequence

Boolean

Either literal true or false literal

Unit

Corresponds to No value

Null

Null or empty reference

Nothing

Each of the other subtypes of the type; Include no value

Any

Any type of super type; Any object is any type

Anyref

Super type of any reference type

All of the data types listed above are objects. There are no original types, such as java. This means that you can call the methods on Int,long and so on Scala base literal:

The text rules used in Scala are simple and intuitive. This section explains the basic text in all Scala. Integer value

Integer literals are usually int types, or the type Dragon is followed by the L or l suffix. Here are some integer literals:

0
035
0777L
Floating-point type

A floating-point literal is a float type followed by a floating-point type suffix f or f, or a double type. Here are some floating-point literals:

1.0e100
.1
Boolean type

Boolean literals True and false are members of a Boolean type. Symbolic literal value

The symbolic constant ' x is shorthand for the expression Scala. Symbol ("X"). Symbol is a class, which is defined as follows.

Package Scala
Final Case Class Symbol private (Name:string) {
Override def tostring:string = "'" + Name
}
Character

Character literals are single characters enclosed in quotes. The character is a printable Unicode character or an escape sequence description. Here are some character literals:

' u0041 '
'
'
'         '
String constants

A string constant is a sequence of characters in double quotes. A character or a printable Unicode character or an escape sequence description. Here are some strings:

"Hello,
world! "
"This string contains a" character.
Multi-line string

The multiline string is contained in the Sanchong quote "character sequence" ... "". A sequence of characters is arbitrary, except that it can contain three or more consecutive quote characters only at the end.

The character may not be printable, and a new line or other control character is allowed. Here is a multiline string:

"" "The present string
Spans three
Lines. "" "
Null value

Null is Scala. A null type is a value, so this reference type is compatible. It indicates that the reference value refers to a special "empty" object. Escape sequence:

The following escape sequences are in characters and strings.

Escape sequence

Unicode

Describe

u0008

BACKSPACE BS

u0009

Horizontal tab HT

u000c

Page Change ff

F

u000c

Page Change ff

u000d

Carriage return CR

"

u0022

Double Reference "

'

u0027

A single reference.

\

u005c

Back slash

The use of Unicode between 0 and 255 characters can also be escaped by a octal, that is, a sequence of up to three octal characters after a backslash "". The following examples illustrate some of the escape character sequences:

Object Test {
def main (args:array[string]) {
println ("Hello World")
" );
}

When the above code is compiled and executed, it produces the following results:

Hello World

The variable is simply reserving the memory location to store the value. This means that when you create a variable, you reserve some space in memory.

Based on the variable data type, the compiler allocates the memory and determines what can be stored in the retention memory. Thus, by assigning variables of different data types, you can store integers, decimals, or characters in these variables. Variable declaration

Scala's variable declarations have different syntax, and they can be defined as values, that is, constants or variables. The following is the syntax for defining a variable using the var keyword:

var myvar:string = "Foo"

Here, MyVar uses the keyword VAR declaration. This means that it is a variable that can change the value, and is called a variable variable. The following is the syntax for defining variables using the VAL keyword:

Val myval:string = "Foo"

Here, Myval is declared using the keyword val. This means that it is a variable that cannot be changed, which is called immutable variable. Variable data type:

The variable type is specified after the variable name before it is signed before equals. You can define any type of scala variable by its data type as follows:

Val or val variablename:datatype [= Initial Value]

If you do not specify any of the initial value variables, it is valid as shown below:

var myvar:int;
Val myval:string;
Variable type inference:

When assigning an initial value to a variable, the Scala compiler can calculate the variable type based on the value assigned to it. This is known as variable type inference. Therefore, the declarations that can write these variables are as follows:

var myVar = 10;
Val myval = "Hello, scala!";

Here, by default, MyVar is the int type and will be set to Myval as a string type variable. Multiple tasks:

Scala supports multitasking. If a code block or method returns a tuple, the tuple can be assigned to a Val variable. [Note: Tuples are studied in later chapters.] ]

Val (myvar1:int, myvar2:string) = Pair (+, "Foo")

Type inference gets the correct type:

Val (myVar1, myVar2) = Pair (+, "Foo")
Variable type:

Scala variables can have three different ranges, depending on where they are being used. They can exist in fields, method parameters, and local variables. Here are more information about the scope of application for each type: field:

A field is a variable that belongs to an object. The field is accessed from all methods in the object. Fields can also be specific depending on the access modifier field and the declared object. An object field can be a mutable or immutable type and can be defined using either Var or Val two. Method Parameters:

A parameter of a method is a variable that is used to pass a value within a method when the method is invoked. Method parameters are passed in from the method only, but the passed object can be from outside if there is a reference object from the outside method. Method parameters are always mutable and are defined by the Val keyword. Local variables:

A local variable is a variable declared within a method. Local variables are accessible only in methods, but you can access the objects that create methods, if they are returned from a method. A local variable can be a mutable or immutable type and can be defined using either VAR or val two keywords.

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.