Scala Basics 01: Getting Started with grammar basics

Source: Internet
Author: User
Tags scala ide

Scala REPL

Res1,res2, ... res5 and so on, respectively, indicate the output result. If the result of a computed output is identified as Res2, then the res2 can be used directly in subsequent calls.

Cases:

Scala Worksheek in the Scala IDE

This is a very useful feature provided by the Scala IDE. Its function is the equivalent of Scala REPL. The results can be displayed dynamically.

Input/Output

The output typically uses the print or println function.

The input typically uses the read function.

ReadLine is to read one line of input from the console. When specifying a type, readt,t is the type you want to specify, such as Readint.

Cases:

Val name=readline ("Your name: \ n") Val Age=readint ()

Expressions and values

In Scala, almost all language elements are expressions.

    • println ("Hello wolrd") is an expression.
    • "Hello" + "world" is also an expression.

Declarations and definitions

You can define a constant by Val, or you can define a variable with var. It is recommended to use constants more. The features of functional programming should be used as much as possible in Scala. Use Val as much as possible.

VAL Constant declaration
    • Declare x as type T val x:t
    • Declare x as type T, and assign a value. Val x:t = e (note e denotes an expression)
var variable declaration
    • Declare x as type T var x:t
    • Declare x as type T and assign var x:t = E

Type omitted
    • Val x = E
    • var x = 3

Declaration omitted

Val x1,x2,x3 is equivalent to Val x1;x2;x3

var x1,x2,x3:t = e  //equivalent to var x1:t = Evar X2:t = Evar X3:t = E

def function declaration

In Scala, the last line of the function body is the value of the entire function body.

def func (x1:t1,x2:t2): T = E

If the return type is OK, you do not need to declare the function return value type.

def func (x1:t1,x2:t2) = E

If the defined function has no arguments, the parentheses of the function can be omitted.

def func () = e//equivalent to def func = E

Example: Define the Max function and the Min function.

Example: Define the Add function with the Max function.

Description: Scala does not have "? : "Ternary operator.

Return statement

The return statement indicates that a value is returned, but Scala does not actually need to use the return statement . for a function, the default return value is the last occurrence of a value , without special mention.

If the value you want to return is not the last occurrence, you can add the identifier of the value to "appear" after the function body.

When declaring a function with a return statement, you must declare the type of the return value.

Cases:

Def abd (): T={return}

Main method

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

Object Basic {  def main (args:array[string]) {    //Main method    println ("Hello world!")  }}

Another way is to use app traits.

Object Basic extends app{    //Main method    println ("Hello world!")}

Comments

consistent with Java. use:// with/ * * /

Block statements

The {} block contains a series of expressions. The value of the last expression, which is the value of the entire block statement.

Scala Control statement Conditional expressions

Scala's IF/ELSE syntax structure is the same as Java or C + +.

if (a) Bif (a) B else C

Note: A can be any statement that returns a Boolean value, or the amount of a Boolean value, True execution B, false execution C;

Example: A function to find the minimum value.

def min (x:int,y:int): int={    var a=x    if (x>y) a=y    return a}

Scala can significantly reduce the amount of code:

An if expression can be used to assign a value.

def min (x:int,y:int) = if (x>y) y else x

Original:

def main (args:array[string]) {  var file = "Scala.txt"  if (! args.isempty) file = args (0)  println (file)}

Improved:

def main (args:array[string]) {  val file = if (! Args.isempty) args (0) Else "scala.txt"  println (file)}

Cycle (while/do)

Scala's while is the same as in Java.

The while statement includes the state judgment and the loop body, so long as the current state is judged true, the loop body is executed again;

Make the next state judgment, and judge the loop to terminate when false.

while (A) B

Cases:

var m=3while (m!=0) {  println (m)  m-=1}

The Do statement, in contrast to the while, executes the loop body once, then the state is judged and the state is true.

Executes the loop body, otherwise terminates the loop.

Do B while (A)  

Cases:

var m=3do{  println (m)  M-=1}while (m!=0)

For loop

Scala's for statement is not the same as in Java.

The for expression can be enumerated in various forms with any condition, while the majority of the loop function is implemented in the enumeration process without the use of variables.

For (i <-e) e (i)

The for expression includes the generator (I <-e), the function body e (i).

The generator is the element that iterates through E, and each time the new Val named I is initialized. For each enumeration, the function body e (i) is executed once, and the parameter I is assigned by the enumeration.

E can be a variety of collections, including arrays, columns, expressions, etc., or a range of values with upper and lower bounds:

1 to 4 means:1=<i<=4;

1 until 4 (1=<i<=4-1) (not including upper bounds)

Cases:

For (i<-1 to n)    r = r*ifor (I <-1 to 4)  if (i%2==0)    if (i!=2)      println ("No.") + i)

Description: To is actually a method of 1. 1 to 10 equivalent to 1.to (10)

For (i<-1.to (n))    r = R*i

Advanced for Loop

Nested for statements in Java and other languages require multiple for statements.

for (I<-E1) for (j<-e2) E (I,J)

The For statement implementation nesting requires only one more <-clause to be added.

for (I<-e1;j<-e2) E (I,J)

Cases:

For (i<-1 to 3; j<-1 to 3) print ((10*i + j) + "")

Each generator can take a guard, and the if expression can be embedded directly in the For statement.

For (i<-e1;if a;j<-e2;if B) E (I,J)

Cases:

For (i<-1 to 3; J<-1 to 3 if I! = j) Print ((10*i + j) + "")

Note: If you can have no semicolons before, you can also have semicolons.

The following wording is the same:

For (I-<-1 to i%2==0) println (i) for (I-<-1 to, if i%2==0) println (i) for (I-<-(1 to); if (i%2==0)) PR Intln (i)

Example: You can use any number of definitions to introduce variables that you can use in a loop:

For (i<-1 to 3, from = 4-i, j<-from to 3) print ((10*i + j) + "")

For-deduction

The For statement, in addition to manipulating the enumeration value and releasing the value, can be used to assign a value that records the value of each enumeration in the collection.

For (i <-e) yield e (i)

If E (i) is enclosed in curly braces, yield must be outside the curly braces.

For (i <-e) yield {e (i)}

Example: Such an assigned x is a sequence type.

Val x= for (I <-1 to 4) yield I

The following results are returned in REPL

X:scala.collection.immutable.indexedseq[int] = Vector (1, 2, 3, 4)

That is, X is assigned a sequence of strings.

The set generated by the for derivation is type-compatible with the first generator.

Cases:

for (c<-"Hello"; i<-0 to 1) yield (c + i). tochar//return res0:string = Hieflmlmopfor (i<-0 to 1; c<-"Hello") yie LD (c+i). tochar//return Res1:scala.collection.immutable.indexedseq[char] = Vector (H, E, L, L, O, I, F, M, M, P)

  

Break/continue statements

Scala does not have break statements and continue statements. Scala's built-in control structure specifically removes break and continue for better adaptation to functional programming.

Example: The following Java code implements the ability to look for a string that ends with ". Scala" from a set of strings, but skips a string that begins with "-".

int I=0;boolean foundit=false;while (i <args.length) {    if (Args[i].startwith ("-")) {        i=i+1; continue;    }    if (Args[i].endswith (". Scala")) {        foundit=true;        break;    }    i=i+1;}

In Scala, you typically use the following method to implement break.

1. Use a Boolean control variable.

Example: Use the IF and Boolean variables below to step through the implementation using Scala (not using break and continue) as follows:

var I=0var foundit=falsewhile (i < args.length &&!foundit) {    if (!args (i). StartsWith ("-")) {        if (args (i). EndsWith (". Scala"))  foundit=true    }    i=i+1}

2. Use recursive functions. (Return statement is still not recommended)

Using recursive functions to implement loops in functional programming is a very common method.

Use recursive functions to re-implement the query functionality implemented by the above code:

def searchfrom (i:int): Int =  if (i >= args.length)-1  else if (args (i). StartsWith ("-")) Searchfrom (i+1)  E LSE if (args (i). EndsWith (". Scala")) I  else Searchfrom (i+1) Val i = searchfrom (0)

3. Use the break method in the Breaks object.

If you still want to use Break,scala to define the break control structure in the Scala.util.control package. It is implemented by throwing an exception to the upper call function.

Example: The following gives an example of using break, constantly reading a non-blank line from the screen, if the user enters a blank line, then exits the loop.

Import Scala.util.control.breaks._import Java.io._val in = new BufferedReader (new InputStreamReader (System.in)) breakable {while  (true) {    println ("?")    if (in.readline () = = "") Break  }}

Scala Basics 01: Getting Started with grammar basics

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.