Scala Language Basics

Source: Internet
Author: User
Tags abstract character set comments comparable constant control characters printable characters valid
Scala Language Basics

1. Scala morphology

The character set used by the Scala program is the basic Multilingual plane character set for Unicode, and the following defines the two modes of Scala morphology: Scala mode and XML schema. If not specifically stated, the following descriptions of the Scala symbols refer to the Scala pattern, and the constant character ' C ' refers to the ASCII segment \u0000-\u007f.

In Scala mode, hexadecimal Unicode escape characters are replaced by the corresponding Unicode characters.

Unicodeescape:: = \{\\}u{u} hexdigit hexdigit hexdigit hexdigit

Hexdigit:: = ' 0 ' ... ' 9 ' a ' ... ' f ' a ' ... ' f ', '. '

The symbols are made up of the following types of characters (the Unicode generic category in parentheses):

1. Blank characters: \u0020 | \u0009 | \u000d | \u000a

2. Letters: Including lowercase (Ll), uppercase (LU), Word initial capital (Lt), Other (Lo), Number (Nl), and \u0024‟$‟ and \u005f "_‟, these two letters classified as uppercase

3. Number: ' 0 ' ... ' 9 '

4. Brackets: ' () ' | ' [] ' | ‘{}’。

5. Separators: '. ' ’;’ ‘,’

6. Operator: the 2.Scala Basic syntax is composed of all printable ASCII characters \u0020-\u007f, mathematical symbols (Sm), and other symbols that are not included in the above categories c9>

Case Sensitive:

Scala is as case-sensitive as Java, such as the person and person are the same.

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:class Myfirstscalaclass

Method Name:

The first letter of all method names is in lowercase.
If several words are used to form the name of a method, the first letter of each word should be capitalized.
Example:def mymethodname ()

program file name:

The name of the program file should exactly match the object name.
When you save a file, you should save the object name it uses (remember that Scala is case-sensitive), and append ". Scala" to the file extension. (If the file name 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 for each Scala program.

3.Scala identifiers

There are three ways Scala can construct an identifier. First, the first character is the letter, and subsequent characters are any letters and numbers. This identifier can also be followed by an underscore ‟_‟, followed by any letter and number. Second, the first character is the count character, and subsequent characters are any operator characters. Both of these forms are common identifiers. Finally, identifiers can be any string enclosed in ‟ ' ‟ (the host system may have some limitations on string and legitimacy). This identifier can be made up of any character except the anti-quote.

Character numbers start with letters or underscores, followed by letters or numbers, and symbols "$" are also seen as letters in Scala. However, identifiers that begin with "$" are used for flags produced by the reserved Scala compiler, and applications should avoid using "$" identifiers to avoid conflicts.

Scala's naming conventions are similar to Java, with the first character lowercase, such as toString. The first character of the class name is also capitalized. You should also avoid using the following underlined markers to avoid collisions. The symbol designator contains one or more symbols, such as +,:,? such as

When implemented within Scala, an escaped marker is used, such as:->, which uses $colon $minus$greater to represent the symbol. So if you need to access the:-> method in Java code, you need to use Scala's internal name $colon $minus$greater.

A mixed glyph consists of a character number marker followed by one or more symbols, such as the name of unary_+ as the internal implementation of the Scala pair + method. Literal markers use "defined strings, such as ' x ' yield '."

You can use any valid Scala marker between "Scala" to interpret them as a Scala marker, a typical yield method using Thread, in Scala you can't use Thread.yield () because yield is SCA In the keywords in LA, you must use Thread. ' Yield ' () to use this method.

4.Scala keywords

Here are the keywords in Scala, and note that you cannot use keywords to name variables.

5.Scala Comments

Scala's annotations are similar to Java: There are single-line comments, multiline comments, and document comments

Example:

Single-line Comment:

    var lines = Source.fromurl ("http://www.baidu.com"). Getlines ()

Multi-line Comments:

/*
Object EXAM1 {
  def main (args:array[string]): Unit = {
    var lines = Source.fromurl ("http://www.baidu.com") . Getlines ()
    Lines.foreach (println)
  }
*/

Examples of document annotations:

/**
  * Created by Chen on 2016/3/22.
  * Business: Get www.baidu.com Web Source
  * *


6. blank lines and spaces

In a row with only spaces or comments, Scala considers it a blank line and ignores it. Tags can be separated by spaces or annotations.


7. Line break

Scala is a line-based language. Both semicolons and line breaks can be used as the end of a statement. If you write multiple statements in a row, the semicolon is required. A newline will be considered a special symbol ‟nl‟ if it satisfies the following three conditions:

1. The symbol before the line break is the end of a statement

2. The symbol after line break is the beginning of a statement

3. Symbols in an area that allows multiple statements to end as statements are: constants, identifiers, reserved words, and the following delimiters:

The symbol that can begin as a statement is all Scala symbols except for the following delimiters and reserved words:

The symbol case can begin as a statement only before the class or object symbol.

Multi-line statements conditions of License:

1. The entire Scala source file, except for nested areas where line breaks are blocked

2. Between matching {and}, except for nested areas where line wrapping is prohibited


Multiline statements are forbidden in the following areas:

1. Between matching (and), in addition to line wrapping is allowed for nested areas.

2. Between the matching [and], except for line wrapping is allowed in the nested area.

3. Between the case symbol and the/= symbol that matches it, in addition to the nested areas that are allowed for line breaks.

4. Regions in XML mode.

Note in XML, curly braces {..} is escaped, the string is not a symbol. Therefore, do not close the area when line breaks are allowed.

In general, even if there are multiple lines in a contiguous two non-newline symbol, only one NL symbol is inserted. However, if two symbols are separated by at least one blank line (no printable characters in the line), then two NL symbols are inserted into the two symbols.

The Scala syntax allows an optional NL symbol, but not a semicolon. Wrapping a line in some places does not end an expression or statement. These locations are listed as follows:

Multiple line breaks are allowed in the following locations (it is not possible to change the semicolon):

-Between the condition of the conditional expression or the while loop and the next expression between the-for loop and the next expression-in the type definition or declaration, the following position allows a single line break after the start of the Type keyword:-in a valid continuation of the current statement or expression of the curly brace "{" Before- If the first sign of the downstream line is the beginning of an expression, after the line's infix operator-before a parameter clause-after a callout

Example 1: The following are four legitimate statements that span two lines. The newline symbol in both lines does not end as a statement.

if (x > 0) x 
    = x–1 while
 
(x > 0) x 
    = X/2 for
 
(x <-1 to ten) 
    println (x)
 
type
I Ntlist = List[int]


Example 2: The following code defines an anonymous class

After adding a newline, the same code becomes an object creation and a local code block

New Iterator[int]

{
  private var x = 0
  def hasnext = True
  def next = {x + = 1; x}
}


Example 3: The following code defines an expression:

X < 0 | | X > 10


After adding a newline, it becomes two expressions:

X < 0 | |
X > 10

Example 4: The following code defines a single, Gerty-only function:

def func (X:int)

        (y:int) = x + y


After adding a newline, the same code becomes an abstract function and an illegal statement.

def func (x:int)

     <span style= "White-space:pre" >	</span> (y:int) = x + y


Example 5: The following code is a label-added definition:

@serializable
protected class data{...}

After adding a newline, the same code becomes an attribute tag and a separate statement (which is actually illegal).

@serializable
 
protected class data{...}



8.Scala package definition Package

Scala uses the Package keyword to define packages, and in Scala there are two ways to define code into a package:

The first method:

Package Com.idoshare.scala

The second method:

Package com.idoshare{
  class test{
  }
}


9. references

Scala uses the Import keyword to refer to a package.

For example:

Import scala.io.Source
import scala.xml.XML
import Scala.xml.parsing.ConstructingParser

The import statement can appear anywhere, not only at the top of the file. The effect of import extends from the beginning to the end of the statement block. This can drastically reduce the likelihood of name collisions.

10.Scala data types

Scala has the same data type as Java, and the following table lists the data types supported by Scala:

11.Scala base literal integer literal

An integer literal usually represents an Int type, or a Long type followed by L or L. The value of Int is a range of integers between 231 and 231-1, containing the boundary values. The range of Long values is an integer between 263 and 263-1, containing the boundary value. An integer literal value that exceeds the range above causes a compilation error.

If a literal is expected in the expression that PT is one of Byte, short, or Char, and the value of the integer conforms to the range of the value of that type, the value is converted to the PT type, which is the type of PT. The range of values is as follows:

Byte-27 to 27-1 Short-215 to 215-1 Char 0 to 216-1

Example: Here are some integer literals:

0	0xFFFFFFFF 0777L


Floating- point literals

If the suffix of a floating-point number literal is F or F, then the literal is of type Float, otherwise it is Double. The float type includes all IEEE 754 32-bit single-precision binary floating-point numbers, and the double type includes all IEEE 754 64-bit double-precision binary floating-point values.

If a symbol is preceded by a letter in a floating-point number in a program, then there should be at least one white-space character between the two.

Example: Here are some floating-point literals:

0.0     1e30f    3.14159f    1.0e-100    . 1


boolean literal

Boolean literals True and False are members of the Boolean type


symbolic literal

The symbolic literal is written as: ' < identifier >, here < identifier > can be any letter or number identifier (note: Cannot start with a number). This literal is mapped to a pre-defined class Scala. instance of person.

such as: the symbolic literal ' x ' is the expression Scala. The shorthand for the person ("X"), the symbolic literal is defined as follows:

Package scalafinal Case Class Person Private (name:string) {
   override def tostring:string = "'" + Name
}


character literal

A character literal is a single character enclosed in single quotation marks. Characters can be printable Unicode characters or Unicode characters that are described by an escape sequence.

Example: Here are some character literals:

' A '    ' \u0041 '    \ n ' \    t '

Note that ' \u000a ' is not a valid character constant, because the Unicode conversion has been completed before the literal value is processed, and the Unicode character \u000a (line break) is not a printable character. You can use escape sequences ' \ n ' or octal escape ' \12 ' to represent a newline character.

string literal

String literals are sequences of characters enclosed in double quotation marks. The character must be a printable Unicode character or an escape sequence. If a string literal includes double quotes, the double quotation mark must be an escape character, such as: \ ". The value of a string literal is an instance of a class string.

Example: Here are some string literals

"Hello,\nworld!" "
This string contains a \ "character."


multiline string literal  

Multiline string literal is a sequence of characters enclosed by three double quotes "" "..." ". The character sequence is any sequence of characters except for three   double quotes. Characters must not necessarily be printable; line breaks or other control characters are also   available. The unicode  escape sequence is also possible, but the escape sequence is not parsed.  

Example  :  the following is a multi-line string literal:

 

The above statement produces the following string:

the present string spans three lines. 
The

Scala Library includes a tool method  stripmargin, which can be used to remove whitespace from the beginning of a multiline string. Stripmargin default to ' | ' Character as a connector.  

expression:

 "" "The present string |spans three |lines." ". Stripmargin 

value:

the present string spans three lines.
     


Stripmargin method is defined in class  scala.runtime.richstring. Because of the predefined implicit conversions from  String  to  RichString , this method can be applied to all strings.

 

 

Null value

The null value is Scala. The Null type.

Scala.null and scala.nothing are special types that handle some of the "boundary conditions" of Scala's object-oriented type system in a unified manner.

A null class is a type of null-referenced object, which is a subclass of each reference class (a class that inherits from Anyref). Null incompatible value type.

Scala escape character

The following table lists the common escape characters:

Unicode characters between 0 and 255 can be represented by an octal escape sequence, that is, a backslash ‟\‟ followed by a maximum of three octal.

In a character or string, a backslash and subsequent character sequences cannot form a valid escape sequence, resulting in a compilation error.


The following examples demonstrate the use of some escape characters:

Object Test {
   def main (args:array[string]) {
      println ("hello\tworld\n\n");
   }
}


12. value types

Each value in Scala has a type in the following format:

Single case type

The singleton type has the form P.type , p is a path that points to an expectation with Scala. Anyref a consistent value. Type refers to a set of null or P-represented values.

A stable type refers to either a singleton type or a feature Scala. The subtype of the Singleton.

Type mapping

Type mapping t#x refers to the type member X of type T. If x points to an abstract type member, then T must be a stable type.

type indication

Type indication refers to a named value type. It can be simple or limited. All of these type indications are shorthand for type mappings.

The unqualified type name T that is bound to a class, object, or Package C is c.this. a shorthand for type #t unless the type T is part of a type pattern. T in the latter is shorthand for c#t. If T is not bound to a class, object, or package, then T is the shorthand for the εtype#t.

A qualified type is just a p.t form, p is a path, and T is a type name. This type indicates equivalent to type mapping p.type #t.

Example: Here are some type indications and extensions. We assume a local type parameter T, a value maintable with a type member Node, and a standard class Scala. Int

T	<span style= "White-space:pre" >		</span>ε.type#t
Int	<span style= "White-space: Pre ">		</span>scala.type#int
Scala. Int	<span style= "White-space:pre" >	</span>scala.type#int 
data.maintable.Node	Data.maintable.type#node


parameterized Types

The parameterized type T[U1,..., Un] includes the type indication T and the type parameter U1,..., the Un,n >=1. T must point to a parameter construction method with a parameter type A1,..., an. the type parameter has a nether L1,..., Ln and an upper bound U1,..., Un. The parameterized type must ensure that each parameter is consistent with its bounds: Σli<:ti<:σui, where σ represents [A1:=t1,..., an:=tn].

Example 1: The following are some type definitions (partial):

Class Treemap[a <: comparable[a], b]{...}
Class List[a] {...}
Class I extends Comparable[i] {...}


The following are the correct parameterized types:

Treemap[i, String] 
list[i] 
List[list[boolean]


Example 2: Using the type definition of Example 1, the following is the parameterized type of the error:

Treemap[i]	//Wrong number of arguments 
treemap[list[i], Boolean]	//type parameter out of bounds

Tuple Type

The tuple type (T1,..., Tn) is class Scala. Tuplen[t1,..., Tn] (n>=2) alias form. This type can have an additional comma at the end, for example: (T1,..., Tn,).

A tuple class is a case class whose fields can be accessed using the selector _1,..., _n. There are their abstract functions in the corresponding Product features. These tuple classes and Product features are part of the standard Scala class library in the following form:

    Case class Tuplen[+t1,..., +tn] (_1:t1,..., _n:tn) extends
    productn[t1,..., tn]{}
    trait productn[+t1,..., +tn]{
      override def arity = n
      def _1:t1 ...
      def _n:tn
    }


Dimension Type

Callout type T A1,..., an is to type T plus callout A1,..., an.

Composite type

Composite type T1 with ... with TN {R} refers to an object that owns T1,..., Tn type and modifies {R}. If there is a declaration or definition in the object that overrides the declaration or definition in the constituent type T1,..., Tn, the usual override rules are applied, otherwise the declaration or definition will be so-called "structured". In

In a structured decorated method declaration, the type of any value parameter is simply the type parameter or abstract type contained within the adornment. That is, it must refer to the type parameter of a function itself, or a type definition within the adornment. This restriction does not work on the return type of the function. If there is no modification, an empty decoration is added by default, for example: T1 with ... with Tn is T1 with ... with Shorthand for Tn {}.

A composite type can have only the adornment {R} and no previous component type. Such a type is equivalent to Anyref{r}.


Example: Here is how to declare and use a function with a parameter type that contains a structured declaration adornment.

Case Class Bird (Val name:string) extends Object {
def fly (height:int) = ...
...
}
Case Class Plane (Val callsign:string) extends Object {
def fly (height:int) = ...
...
}
def takeoff (
Runway:int,
r: {val callsign:string; def fly (Height:int)}) = {Tower.print (r.callsign + "Reque  STS Take-off on Runway "+ runway) Tower.read (R.callsign +" was clear for Take-off ")
r.fly (+)
}
Val Bird = new Bird ("Polly The Parrot") {val callsign = name}
val a380 = new Plane ("TZ-987") takeoff (Bird) takeoff (
, A380)

Although Bird and Plane do not have any parent class except Object, the takeoff parameter R can accept any object that declares the value callsign and the function fly, with a function that is decorated with a structured declaration.

infix type

The infix type T1 op T2 is applied by an infix operator op to two operands T1 and T2. This type is equivalent to the type Application Op[t1, T2]. The infix operator can be any identifier other than *, because * is reserved as a suffix of the repeating parameter type.

function Type

Type (T1,..., tn) + U represents those functions whose parameter type is T1,..., Tn and produces a result of type U. If there is only one parameter type then (T) =>u can be abbreviated to T=>U. The type (=>t) =>u represents a Bogwang parameter with type T and produces a result of type U. The function type is right associative, for example: S=>t=>u is equivalent to S=> (t=>u).

A function type is a shorthand for the class type that defines the Apply function. For example, n-type function types (T1,..., Tn) and U are shorthand for class functionn[t1,..., Tn,u]. These class types with n 0 to 9 are defined in the Scala library as follows:

    Package Scala
    trait functionn[-t1,...,-Tn, +r] {
      def apply (x1:t1,..., xn:tn): R
      override def toString = "< Function> "
    }

Therefore, the function type and the result type are covariant, and the parameter type is contravariant.


The Bogwang function type (=>t) =>u is the abbreviated form of the class type Bynamefunction[t,u], as defined below:

    Package Scala
    trait bynamefunction[-t, +r] {
      def apply (x: = = T): R
      override def toString = "<FUNCTION&G t; "
    }

Existing Types

The existing type has the form of T forsome {q}, and Q is a sequence of type declarations. Set T1[TPS1]>:L1<:U1,..., Tn[tpsn]>:ln<:un is the type declared in Q (any type parameter part [TPSI] can have no). Each type of TI domain contains the type T and the existing clause Q. The type variable ti is called in the type T forsome {Q} is bound. A type variable that is not bound in T is called free in T.

The example of a class of T forsome {Q} is that the class σt,σ is an iteration on the T1,..., tn, and there are σli<:σti<:σui for each i. The collection of values for the existing type T forsome{Q} is the collection of all of its type instance values.

The forsome of T {Q} is a class instance σt,σ is an iteration on [T‟1/t1,..., t‟n/tn, and each t‟i is a new abstract type between Σli and Σui.

13.Scala variables

A variable is a handy placeholder for referencing a computer's memory address, which takes up a certain amount of memory when it is created. Based on the variable data type, the operating system allocates memory and decides what will be stored in the reserved memory. So, by assigning different data types to variables, you can store integers, decimals, or letters in these variables. Variable declaration

Before learning how to declare variables and constants, let's begin by understanding some variables and constants.

A variable: The amount of the value that may change during a program's operation is called

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.