The first step: learning to use the Scala interpreter
The easiest way to start Scala is to use the Scala interpreter, which is an interactive "shell" that writes Scala expressions and programs. Scala needs to be installed before using Scala, so you can refer to the first Steps to Scala content.
You can enter Scala in the command prompt to use it:
$ scala Welcome to Scala version 2.9.2.
Type in expressions to has them evaluated.
Type:help for more information.
Scala>
After you enter the expression, such as 1 + 2, and knock the carriage return:
1 2
The Interpreter will print:
Res0:int = 3
This line includes:
? An automatically generated or user-defined name that describes the computed value (Res0, which represents the result 0),
? A colon (:), followed by the type of the expression (INT),
? An equal sign (=),
? The result of the calculation of an expression (3).
The int type refers to the class int of the Scala package. The packages in Scala are similar to those in Java: They partition the global namespace and provide a mechanism for information hiding. The value of the class int corresponds to the int value of java.
Step two: Define the values of some variable class int that correspond to the int value of java. In a broader sense, all Java primitive types have classes in the Scala package. For example, Scala. Boolean corresponds to the boolean of Java.
Scala. Float corresponds to the Java float. When you compile your Scala code into Java bytecode, the Scala compiler will use the original Java type to get the performance benefits it brings. 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:
3
Res1:int = 9
Print the necessary, but not just this, Hello, world!. Input:
Scala> println ("Hello, world! ")
Hello, world!.
The println function prints the string passed to it on the standard output, just like the System.out.println in Java.
Step two: Define some variables
Scala has two types of variables, Val and var. Val is similar to the final variable in Java. Once initialized, Val can no longer be assigned a value. In response, Var is like a non-final variable in Java. var can be assigned multiple times during its life cycle . The following is a Val definition:
" Hello, world!. "
msg:java.lang.String = Hello, world!
This statement introduces MSG as a string "Hello, world!" 's name. The type is java.lang.String, because Scala's strings are implemented by the Java string class.
Because Scala has the ability to automatically understand the types you omit, that is, type inference: inference. The Scala interpreter (or compiler) can infer the type. However, if you want to, you can also explicitly define the type, and maybe sometimes you should do the same. Explicit type labeling not only ensures that the Scala compiler infers the type you prefer, but also serves as a useful document for future code readers. In contrast, the types of variables in Scala are separated by colons after their names. Such as:
" Hello again, world! "
Msg2:java.lang.String = Hello again, world!
Because the simplified name of the Java.lang type is also visible in the Scala program, it can be simplified to:
" Hello yet again, world! "
Msg3:string = Hello yet again, world!
Back to the original MSG, now that it is defined, you can use it as you think, such as:
scala> println (msg) Hello,World!
What you can't do with MSG is to give it a value, because it's Val, not var. Attempting to assign a new value to MSG will give an error:
" Goodbye Cruel world! " <console>:5"Goodbye cruel world! "
If you need a variable that can be re-assigned, you must use Var to define it. Such as:
var " Hello, world!. " = Hello, world! Scala " Leave me alone, world! " = Leave me alone, world!
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 will respond to a vertical bar on the next line.
" The next line. " is the next line.
If you realize that you have entered something wrong and the interpreter is still waiting for you to enter more, you can cancel it by pressing the two-time carriage return:
scala> val oops = | | New command. Scala>
Step three: Define some functions
Now that you've used Scala's variables, you might want to write some functions. Here's how it's done in Scala:
if Else xmax: (int,int) Int
the definition of a function begins with Def . The function name, in this case Max, followed by a colon-delimited list of arguments in parentheses. Each function parameter must have a type callout with a prefix colon, because the Scala compiler has no way to infer the function parameter type, and you will see another ": Int" type callout after the parentheses in the Max argument list. This thing defines the result type of the MAX function: result of type followed by the function result type is an equal sign and a pair of curly braces that contain the body of the function.
The equals sign in front of the function body suggests that in the world view of functional programming, a function defines an expression that can produce a value. The basic structure of the function is shown inside:
The basic composition of Scala functions
Sometimes the Scala compiler will need you to define the result type of the function. For example, if a function is recursive, you have to 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. Similarly, if a function consists of only one sentence, you can optionally not write curly braces. In this way, you can write the Max function like this:
if Else y
MAX2: (int,int) Int
Once you have defined the function, you can call it with its name, such as:
Scala> Max (355
There are also function definitions that have neither parameters nor return useful results:
Scala> def greet () = println ("Hello, world! " ) Greet: () Unit
When you define the greet () function, the interpreter responds with a greet: () Unit. "Greet" is of course the function name. blank parentheses indicate that the function has no parameters. The unit is the result type of the greet. The result type of the unit refers to a function that does not return a useful value. Scala's unit type is closer to the void type of Java, and virtually every method of returning void in Java is mapped to the method of returning the unit in Scala. So the result type is the unit method, which only runs for their side effects
Next, you'll put the Scala code in a file and execute it as a script. If you want to leave the interpreter, type: Quit or: Q.
Scala> : Quit $
Fourth step: write some Scala scripts
Although Scala is designed to help programmers build very large-scale systems, it can also be scaled down to the size of scripts. A script is a sequence of sentences placed in a file that is often executed. Place the following code in the Hello.scala file:
println ("Hello, World, from a script!")
And then run
$ Scala Hello.scala
And then you'll get another toast.
Hello, world, from a script!
through Scala's array named args, you get command-line arguments that are passed to the Scala script . In Scala, the array starts with zero and accesses an element by specifying an index in parentheses. So the first element in Scala's array steps is steps (0), not steps[0 in Java]. As a test, enter the following into the new file Helloarg.scala:
Greet the first parameter
println ("Hello," + args (0) + "!")
Then run:
$ Scala Helloarg.scala Planet
In this command, "planet" is passed as a command-line argument and is accessed as args (0) in the script. So, you will see:
Hello, planet!.
Note that the script includes a comment. The Scala compiler ignores characters from//start to end of line and between/* and/*. This example also demonstrates the connection of string using the + operator. This is the same as your expectations. Expression "Hello," + "world!" The string "Hello, world!" will be generated.
Fifth step: Use while loop;
To try while, enter the following code in the Printargs.scala file:
var 0 while (I < args.length) { println (args (i)) 1}
Note Although the examples in this section help explain the while loop, they do not demonstrate the best Scala style. In the next paragraph, you'll see a better way to avoid enumerating arrays with indexes.
This script starts with the variable definition, var i = 0. Type inference determines that the type of I is Scala. Int, because this is the type of its initial value, 0. The while structure in the next line causes the code block (the code between the braces) to be executed repeatedly until the Boolean expression I < Args.length is false. Args.length gives the length of the args array. The code block contains two sentences, each indented two spaces, which is the recommended indentation style for Scala. The first sentence, println (args (i)), outputs the I command-line arguments. The second sentence, i + = 1, let I self-increment one. Note that Java's ++i and i++ do not work in Scala and are to be added in Scala, either i = i + 1, or i + = 1. Run the script with the following command:
is fun
You will see:
Scala is fun
Note Scala, like Java, must enclose the Boolean expression for while or if in parentheses. (In other words, it can't be written in Scala like in Ruby: if I < 10.) The IF (I < 10) must be written in Scala. Another point similar to Java is that if the code block has only one sentence, the braces are optional,
And even though you don't see it, Scala uses semicolons to separate sentences like Java, but Scala's semicolons are often optional.
Sixth step: Using foreach and for enumeration
Although you may not realize that when you write the while loop in the previous step, you are programming with the instruction: imperative style. Directive style, is that you often use the language such as java,c++ and C, the style of a one-time command-type commands, with a loop to enumerate, and often change the sharing between the different functions of the State,
Scala allows you to program programmatically, but as you gain insight into Scala, you may often find yourself programming in a more functional style: functional.
One of the main features of functional languages is that functions are the first type of structure, which is true in Scala. For example, another (much simpler) way to print each command-line parameter is:
Args. foreach (arg = println (ARG))
In this line of code, you raise the Foreach method on args and pass it to the function. In this example, you pass in the function text with a parameter called ARG: Functions literal. The function body is println (ARG). If you enter the above code into the new file Pa.scala, and use the command to execute:
is nice
You will see:
Concise is Nice
If you prefer a concise rather than an explicit style, you can fully appreciate the advantages of Scala's special simplicity. If the function text consists of a single sentence with one argument, you do not need to explicitly name and specify parameters. 11
In this way, the following code is also valid:
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. Grammar demonstrations in the
To try to guide you in a functional direction, Scala has only a functional approximation of the instruction for (called for expression: expression). To create a new file Forargs.scala, enter the following code:
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). (because it's always Val, you just have to write Arg, not Val Arg.) 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.
You can assume that the <-symbol stands for "one". If you want to read for (Arg<-args), attend "Arg in args".
If you execute the Forargs.scala script:
for in args
can see:
for in args
Scala's first step