Scala Programming (i)

Source: Internet
Author: User

About Scala

Scala is a "stretched language", which can be changed and grown with the needs of the user. Scala can be used in a wide range of programming tasks, as small as scripts to build systems. Scala runs on the standard Java platform and can interact seamlessly with all Java libraries. It adds object-oriented and functional programming concepts to statically typed languages . Scala can nurture new types and new control structures, making it more like the built-in type and control structure, which does not provide all the things you might need in a "perfect" language, but rather puts the tools that make these things in your hands.

Scala Programming Overview

Scala Interpreter

The Scala interpreter is an interactive "shell" that writes Scala expressions and programs, entering an expression in the interpreter that evaluates the expression and prints the result. You can open the interpreter by entering Scala in the terminal:

?  ~  scalawelcome to Scala version 2.11.7 (Java HotSpot (TM) 64-bit Server VM, Java 1.8.0_65). Type in expressions to has them evaluated. Type:help for more information.

After you enter an expression and return:

Scala> 1 + 2res0:int = 3

The results that the interpreter prints after evaluating an expression include:

• An auto-generated or user-defined name Description calculated value (RES0, indicating result 0)

• A colon (:) followed by the type of expression (INT),

• An equal sign (=),

• The result of calculating an expression (3).

The ResX identifier will also be used in subsequent lines of code. For example, since Res0 was previously set to 3,RES0 * 3 is 9:

Scala> Res0 * 3res1:int = 9

Variable

Scala has two types of variables, Val and var. Val Once the initialization is re-assigned, VAR can be assigned multiple times in its lifetime. The following is a Val definition:

scala> val msg = "Hello world" msg:string = Hello World

This statement introduces MSG as the name of the string "Hello World". The type is string because Scala's strings are implemented by the Java string class. Scala can automatically understand the type of ellipsis. In this example, a string literal is used to initialize the type of the Msg,scala inference Msg. However, you can also explicitly define types, and explicit type callouts will not only ensure that the Scala compiler infers the type you prefer, but also serves as a useful document for future code readers. The type of the variable in Scala is separated by a colon after its name. Such as:

scala> val msg2:string = "Hello world" msg2:string = Hello World

Since MSG is Val is not Var, it can no longer be assigned, otherwise it will error:

scala> msg = "Hello" <console>:11:error:reassignment to val       msg = "Hello"           ^

If you need to re-assign a value, you should use VAR to define the variable:

scala> var msg3 = "Hello world" msg3:string = Hello worldscala> msg3 = "Hello" msg3:string = Hello

To enter something that spans more than one line, as long as a line is lost. If the end of the line is not finished, the interpreter responds to a vertical bar on the next line:

scala> var multline =     | ' next line ' multline:string = next line

If you enter something wrong, and the interpreter is still waiting for more input, you can cancel it by pressing ENTER two times:

scala> val oops =     |     | You typed the lines of the blank.  Starting a new command.

Function

The function definition in Scala:

Scala> def Max (X:int, y:int): Int = {     | if (x > Y) x     | else y     |} Max: (X:int, Y:int) Int

Basic structure of the function:

Sometimes the Scala compiler will need to define the result type of the function. For example, if a function is recursive, you must explicitly define the function result type. In Max's case, however, you don't have to write the result type, and the compiler can infer it. If the function consists of only one sentence, you can optionally not write the curly braces:

Scala> def max2 (x:int, y:int) = if (x > Y) x Else ymax2: (X:int, Y:int) Int

Once a function is defined, it can be called with its name, such as:

Scala> max (res3:int) = 2

There are also function definitions that have neither parameters nor return useful results:

scala> def hello () = println ("Hello World") Hello: () Unit

When defining the Hello () function, the interpreter responds with a Hello: () Unit. "Hello" is the function name. Blank parentheses indicate that the function has no parameters. The Unit is the result type of hello. The result type of the Unit refers to a function that does not return a useful value. Therefore, the result type is the Unit method, which only runs for their side effects. In the example of Hello (), the side effect is to print a polite auxiliary word on the standard output.

Script

The way to run the script is Scala [File.scala], and Scala's array named args gets the command-line arguments passed to the Scala script. In Scala, the array starts at 0 and accesses an element by specifying the index in parentheses.

While loop; if judgment; foreach and for enumeration

Write the while and if in the following way:

var i = 0while (i < args.length) {  if (i! = 0)    print ("")  print (args (i))  i + = 1}

Like this one-time command-type commands, with loops to enumerate, and often change the state of sharing between different functions called instruction-style programming , Scala allows instruction-type programming, but functional style programming more comfortable:

Args.foreach (arg = println (ARG))

In this line of code, the Foreach method is raised in args and passed into the function, passing in a function literal with a parameter called ARG, which is println (ARG).

The Scala interpreter infers that the type of arg is string, because string is the element type of the array that called foreach. To explicitly add a type name, enclose the parameter in parentheses:

Args.foreach ((arg:string) = println (ARG))

  If the function text consists of a single sentence with one argument, you do not even need to explicitly name and specify parameters :

Args.foreach (println)

All in all, the syntax of the function text is the list of named arguments in parentheses, the right arrow, and then the body of the function:

How to use the instruction in Scala:

for (Arg <-args)  println (ARG)

The parentheses after "for" in this expression contain Arg<-args. <-to the right is the familiar args array. <-to the left is "Arg", the name of Val (not Var). Although Arg may feel like Var, he will get a new value at every enumeration, but it is indeed val:arg cannot be re-assigned in the function body of the for expression. Instead, for each element of the args array, a new arg Val will be created and initialized to the element value, and then the for function body will be executed.

Scala Programming (i)

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.