Scala Tutorial (Hướng dẫn Scala)

LI
lienhejb
0 downloads
116
0

Document content

Page 3

ABOUT THE TUTORIAL ScalaTutorial Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates features of object-oriented and functional languages. This tutorial gives a great understanding on Scala. Audience This tutorial has been prepared for the beginners to help them understand programming Language Scala in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Scala from where you can take yourself to next levels. Prerequisites Scala Programming is based on Java, so if you are aware of Java syntax, then it's pretty easy to learn Scala. Further if you do not have expertise in Java but you know any other programming language like C, C++ or Python, then it will also help in grasping Scala concepts very quickly. Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com TUTORIALS POINT Simply Easy Learning

Page 4

Table of Content Scala Tutorial........................................................................... 2 Audience.................................................................................. 2 Prerequisites............................................................................ 2 Copyright & Disclaimer Notice.................................................. 2 Scala Overview ........................................................................ 8 Scala is object-oriented: ............................................................................ 8 Scala is functional:..................................................................................... 8 Scala is statically typed: ............................................................................ 8 Scala runs on the JVM: ............................................................................. 8 Scala can Execute Java Code:.................................................................. 9 Scala vs Java: ........................................................................................... 9 Scala Web Frameworks: ........................................................................... 9 Scala Environment Setup....................................................... 10 Installing Scala on Windows: ................................................................... 10 STEP (1): JAVA SETUP: ......................................................................... 10 STEP (2): SCALA SETUP: ..................................................................... 10 Installing Scala on Mac OS X and Linux.................................................. 11 STEP (1): JAVA SETUP: ........................................................................ 11 STEP (2): SCALA SETUP: ..................................................................... 11 Scala Basic Syntax ................................................................ 13 First Scala Program:................................................................................ 13 INTERACTIVE MODE PROGRAMMING: ............................................... 13 SCRIPT MODE PROGRAMMING:.......................................................... 13 Basic Syntax:........................................................................................... 14 Scala Identifiers: ...................................................................................... 15 ALPHANUMERIC IDENTIFIERS............................................................. 15 OPERATOR IDENTIFIERS ..................................................................... 15 MIXED IDENTIFIERS.............................................................................. 15 LITERAL IDENTIFIERS........................................................................... 15 Scala Keywords:...................................................................................... 15 Comments in Scala ................................................................................. 16 Blank Lines and Whitespace: .................................................................. 16 Newline Characters: ................................................................................ 16 Scala Packages:...................................................................................... 16 Scala Data Types................................................................... 18 Scala Basic Literals: ................................................................................ 18 INTEGER LITERALS .............................................................................. 19 TUTORIALS POINT Simply Easy Learning

Page 5

FLOATING POINT LITERALS................................................................ 19 BOOLEAN LITERALS............................................................................. 19 SYMBOL LITERALS ............................................................................... 19 CHARACTER LITERALS........................................................................ 19 STRING LITERALS ................................................................................ 19 MULTI-LINE STRINGS ........................................................................... 19 THE NULL VALUE.................................................................................. 20 ESCAPE SEQUENCES:......................................................................... 20 Scala Variables ...................................................................... 21 Variable Declaration ................................................................................ 21 Variable Data Types: ............................................................................... 21 Variable Type Inference: ......................................................................... 22 Multiple assignments: .............................................................................. 22 Variable Types:........................................................................................ 22 FIELDS:................................................................................................... 22 METHOD PARAMETERS: ...................................................................... 22 LOCAL VARIABLES:............................................................................... 22 Scala Access Modifiers .......................................................... 23 Private members: .................................................................................... 23 Protected members: ................................................................................ 23 Public members:...................................................................................... 24 Scope of protection:................................................................................. 24 Scala Operators ..................................................................... 25 Arithmetic Operators:............................................................................... 25 Example: ................................................................................................. 25 Relational Operators:............................................................................... 26 Example: ................................................................................................. 27 Logical Operators: ................................................................................... 27 Example: ................................................................................................. 27 Bitwise Operators: ................................................................................... 28 Example .................................................................................................. 29 Assignment Operators:............................................................................ 30 Example: ................................................................................................. 30 Operator Precedence in Scala:................................................................ 31 Scala IF…ELSE Statements .................................................. 33 The if Statement: ..................................................................................... 33 SYNTAX: ................................................................................................. 33 EXAMPLE:............................................................................................... 34 The if...else Statement:............................................................................ 34 TUTORIALS POINT Simply Easy Learning

Page 6

SYNTAX:................................................................................................. 34 EXAMPLE: .............................................................................................. 34 The if...else if...else Statement: ............................................................... 35 SYNTAX: ................................................................................................. 35 EXAMPLE:............................................................................................... 35 Nested if...else Statement: ...................................................................... 36 SYNTAX: ................................................................................................. 36 EXAMPLE:............................................................................................... 36 Scala Loop Types .................................................................. 37 while loop ................................................................................................ 38 Syntax: .................................................................................................... 38 Flow Diagram: ......................................................................................... 38 Example: ................................................................................................. 39 do…while loop......................................................................................... 39 Syntax: .................................................................................................... 39 Flow Diagram: ......................................................................................... 40 Example: ................................................................................................. 40 for loop .................................................................................................... 41 The for Loop with Ranges ....................................................................... 41 Example: ................................................................................................. 41 The for Loop with Collections .................................................................. 42 Example: ................................................................................................. 43 The for Loop with Filters .......................................................................... 43 Example: ................................................................................................. 43 The for Loop with yield: ........................................................................... 44 Example: ................................................................................................. 44 Loop Control Statements: ........................................................................ 45 break statement....................................................................................... 45 Syntax: .................................................................................................... 45 Flow Diagram: ......................................................................................... 46 Example: ................................................................................................. 46 Breaking Nested Loops: .......................................................................... 47 Example: ................................................................................................. 47 Infinite Loop: ............................................................................................ 48 Scala Functions ..................................................................... 49 Function Declarations:............................................................................. 49 Function Definitions: ................................................................................ 49 Calling Functions: .................................................................................... 50 Scala Closures....................................................................... 57 TUTORIALS POINT Simply Easy Learning

Page 7

Scala Strings.......................................................................... 58 Creating Strings:...................................................................................... 58 String Length: .......................................................................................... 59 Concatenating Strings: ............................................................................ 59 Creating Format Strings: ......................................................................... 60 String Methods: ....................................................................................... 60 Scala Arrays........................................................................... 64 Declaring Array Variables: ....................................................................... 64 Processing Arrays: .................................................................................. 65 Multi-Dimensional Arrays:........................................................................ 66 Concatenate Arrays:................................................................................ 66 Create Array with Range: ........................................................................ 67 Scala Arrays Methods: ............................................................................ 68 Scala Collections.................................................................... 69 Basic Operations on List:......................................................................... 70 Concatenating Lists: ................................................................................ 71 Creating Uniform Lists: ............................................................................ 72 Tabulating a Function: ............................................................................. 72 Reverse List Order: ................................................................................. 72 Scala List Methods: ................................................................................. 73 Basic Operations on Set: ......................................................................... 76 Concatenating Sets: ................................................................................ 76 Find max, min elements in Set: ............................................................... 77 Find common values in Sets:................................................................... 77 Scala Set Methods: ................................................................................. 78 Basic Operations on Map: ....................................................................... 81 Concatenating Maps................................................................................ 81 Print Keys and Values from a Map: ......................................................... 82 Check for a Key in Map: .......................................................................... 82 Scala Map Methods:................................................................................ 83 Iterate over the Tuple: ............................................................................. 86 Convert to String:..................................................................................... 87 Swap the Elements:................................................................................. 87 Using getOrElse() Method: ...................................................................... 88 Using isEmpty() Method: ......................................................................... 89 Scala Option Methods: ............................................................................ 89 Find Min & Max valued Element: ............................................................. 91 Find the length of the Iterator:.................................................................. 91 Scala Iterator Methods: ........................................................................... 92 TUTORIALS POINT Simply Easy Learning

Page 8

Example: ................................................................................................. 94 Scala Classes & Objects ........................................................ 96 Extending a Class:................................................................................... 97 Singleton objects: .................................................................................... 98 Scala Traits .......................................................................... 100 When to use traits?................................................................................ 101 Scala Pattern Matching ........................................................ 102 Matching Using case Classes:............................................................... 103 Scala Regular Expressions .................................................. 105 Forming regular expressions: ................................................................ 106 Regular-expression Examples:.............................................................. 107 Scala Exception Handling .................................................... 110 Throwing exceptions:............................................................................. 110 Catching exceptions: ............................................................................. 110 The finally clause:.................................................................................. 111 Scala Extractors ................................................................... 112 Pattern Matching with Extractors: .......................................................... 113 Scala Files I/O...................................................................... 114 Reading line from Screen: ..................................................................... 114 Reading File Content:............................................................................ 115 TUTORIALS POINT Simply Easy Learning

Page 9

C1HAPTER Scala Overview S cala, short for Scalable Language, is a hybrid functional programming language. It was created by Martin Odersky and it was first released in 2003. Scala smoothly integrates features of object-oriented and functional languages and Scala is compiled to run on the Java Virtual Machine. Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability. Here is the important list of features, which make Scala a first choice of the application developers. Scala is object-oriented: Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits which will be explained in subsequent chapters. Classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance. Scala is functional: Scala is also a functional language in the sense that every function is a value and because every value is an object so ultimately every function is an object. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. These concepts will be explained in subsequent chapters. Scala is statically typed: Scala, unlike some of the other statically typed languages, does not expect you to provide redundant type information. You don't have to specify a type in most cases, and you certainly don't have to repeat it. Scala runs on the JVM: Scala is compiled into Java Byte Code, which is executed by the Java Virtual Machine (JVM). This means that Scala and Java have a common run-time platform. You can easily move from Java to Scala. TUTORIALS POINT Simply Easy Learning

Page 10

The Scala compiler compiles your Scala code into Java Byte Code, which can then be executed by the scala command. The scala command is similar to the java command, in that it executes your compiled Scala code. Scala can Execute Java Code: Scala enables you to use all the classes of the Java SDK's in Scala, and also your own, custom Java classes, or your favourite Java open source projects. Scala vs Java: Scala has a set of features, which differ from Java. Some of these are:  All types are objects.  Type inference.  Nested Functions.  Functions are objects.  Domain specific language (DSL) support.  Traits.  Closures.  Concurrency support inspired by Erlang. Scala Web Frameworks: Scala is being used everywhere and importantly in enterprise web applications. You can check few of the most popular Scala web frameworks:  The Lift Framework  The Play framework  The Bowler framework TUTORIALS POINT Simply Easy Learning

Page 11

CHAPTER2 Scala Environment Setup T he Scala language can be installed on any UNIX-like or Windows system. Before you start installing Scala on your machine, you must have Java 1.5 or greater installed on your computer. Installing Scala on Windows: STEP (1): JAVASETUP: First, you must set the JAVA_HOME environment variable and add the JDK's bin directory to your PATH variable. To verify if everything is fine, at command prompt, type java -version and press Enter. You should see something like the following: C:\>java -version java version "1.6.0_15" Java(TM) SE Runtime Environment (build 1.6.0_15-b03) Java HotSpot(TM) 64-Bit Server VM (build 14.1-b02, mixed mode) C:\> Next, test to see that the Java compiler is installed. Type javac -version. You should see something like the following: C:\>javac -version javac 1.6.0_15 C:\> STEP (2): SCALA SETUP: Next, you can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded scala-2.9.0.1-installer.jar and put it in C:/> directory. Make sure you have admin privilege to proceed. Now, execute the following command at command prompt: C:\>java -jar scala-2.9.0.1-installer.jar C:\> Above command will display an installation wizard, which will guide you to install scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where scala will be installed. I selected default given path C:\Program Files\scala, you can select a suitable path as per your TUTORIALS POINT Simply Easy Learning

Page 12

convenience. Finally, open a new command prompt and type scala -versionand press Enter. You should see the following: C:\>scala -version Scala code runner version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL C:\> Congratulations, you have installed Scala on your Windows machine. Next section will teach you how to install scala on your Mac OS X and Unix/Linux machines. Installing Scala on Mac OS X and Linux STEP (1): JAVA SETUP: Make sure you have got the Java JDK 1.5 or greater installed on your computer and set JAVA_HOME environment variable and add the JDK's bin directory to your PATH variable. To verify if everything is fine, at command prompt, type java -version and press Enter. You should see something like the following: $java -version java version "1.5.0_22" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_22-b03) Java HotSpot(TM) Server VM (build 1.5.0_22-b03, mixed mode) $ Next, test to see that the Java compiler is installed. Type javac -version. You should see something like the following: $javac -version javac 1.5.0_22 javac: no source files Usage: javac <options> <source files> ................................................ $ STEP (2): SCALA SETUP: Next, you can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded scala-2.9.0.1-installer.jar and put it in /tmp directory. Make sure you have admin privilege to proceed. Now, execute the following command at command prompt: $java -jar scala-2.9.0.1-installer.jar Welcome to the installation of scala 2.9.0.1! The homepage is at: http://scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1 ................................................ [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] $ During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type scala -version and press Enter. You should see the following: TUTORIALS POINT Simply Easy Learning

Page 13

$scala -version Scala code runner version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL $ Congratulations, you have installed Scala on your UNIX/Linux machine. TUTORIALS POINT Simply Easy Learning

Page 14

CHAPTER3 Scala Basic Syntax I f you have good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ; line end character is optional. When we consider a Scala program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instant variables mean.  Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.  Class - A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.  Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.  Fields - Each object has its unique set of instant variables, which are called fields. An object's state is created by the values assigned to these fields. First Scala Program: INTERACTIVE MODE PROGRAMMING: Invoking the interpreter without passing a script file as a parameter brings up the following prompt: C:\>scala Welcome to Scala version 2.9.0.1 Type in expressions to have them evaluated. Type :help for more information. scala> Type the following text to the right of the Scala prompt and press the Enter key: scala> println("Hello, Scala!"); This will produce the following result: Hello, Scala! SCRIPT MODE PROGRAMMING: Let us look at a simple code that would print the words Hello, World! object HelloWorld { /* This is my first java program. TUTORIALS POINT Simply Easy Learning

Page 15

* This will print 'Hello World' as the output */ def main(args: Array[String]) { println("Hello, world!") // prints Hello World } } Let's look at how to save the file, compile and run the program. Please follow the steps given below: 1. Open notepad and add the code as above. 2. Save the file as: HelloWorld.scala. 3. Open a command prompt window and go to the directory where you saved the program file. Assume it is C:\> 4. Type 'scalac HelloWorld.scala' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line. 5. Above command will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode, which will run on Java Virtual Machine (JVM). 6. Now, type 'scala HelloWorld' to run your program. 7. You will be able to see 'Hello, World!' printed on the window. C:\> scalac HelloWorld.scala C:\> scala HelloWorld Hello, World! Basic Syntax: About Scala programs, it is very important to keep in mind the following points.  Case Sensitivity - Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala.  Class Names - For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example class MyFirstScalaClass  Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example def myMethodName()  Program File Name - Name of the program file should exactly match the object name. When saving the file, you should save it using the object name (Remember scala is case-sensitive) and append '.scala' to the end of the name (if the file name and the object name do not match your program will not compile). Example: Assume 'HelloWorld' is the object name. Then, the file should be saved as 'HelloWorld.scala'  def main(args: Array[String]) - Scala program processing starts from the main() method, which is a mandatory part of every Scala Program. TUTORIALS POINT Simply Easy Learning

Page 16

Scala Identifiers: All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. There are following four types of identifiers supported by Scala: ALPHANUMERIC IDENTIFIERS An alphanumeric identifier starts with a letter or underscore, which can be followed by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala and should not be used in identifiers. Following are legal alphanumeric identifiers: age, salary, _value, __1_value Following are illegal identifiers: $salary, 123abc, -salary OPERATOR IDENTIFIERS An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #. Following are legal operator identifiers: + ++ ::: <?> :> The Scala compiler will internally "mangle" operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater. MIXED IDENTIFIERS A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier. Following are legal mixed identifiers: unary_+, myvar_= Here, unary_+ used as a method name defines a unary + operator and myvar_= used as method name defines an assignment operator. LITERAL IDENTIFIERS A literal identifier is an arbitrary string enclosed in back ticks (` . . . `). Following are legal literal identifiers: `x` `<clinit>` `yield` Scala Keywords: The following list shows the reserved words in Scala. These reserved words may not be used as constant or variable or any other identifier names. Abstract Case catch class Def Do else extends False Final finally for TUTORIALS POINT Simply Easy Learning

Page 17

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 - : = => <- <: <% >: # @ Comments in Scala Scala supports single-line and multi-line comments very similar to Java. Multi-line comments may be nested, but are required to be properly nested. All characters available inside any comment are ignored by Scala compiler. object HelloWorld { /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ def main(args: Array[String]) { // Prints Hello World // This is also an example of single line comment. println("Hello, world!") } } Blank Lines and Whitespace: A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments. Newline Characters: Scala is a line-oriented language where statements may be terminated by semicolons (;) or newlines. A semicolon at the end of a statement is usually optional. You can type one if you want but you don't have to if the statement appears by itself on a single line. On the other hand, a semicolon is required if you write multiple statements on a single line: val s = "hello"; println(s) ScalaPackages: A package is a named module of code. For example, the Lift utility package is net.liftweb.util. The package declaration is the first non-comment line in the source file as follows: package com.liftcode.stuff TUTORIALS POINT Simply Easy Learning

Page 18

Scala packages can be imported so that they can be referenced in the current compilation scope. The following statement imports the contents of the scala.xml package: import scala.xml._ You can import a single class and object, for example, HashMap from the scala.collection.mutable package: import scala.collection.mutable.HashMap You can import more than one class or object from a single package, for example, TreeMap and TreeSet from the scala.collection.immutable package: import scala.collection.immutable.{TreeMap, TreeSet} TUTORIALS POINT Simply Easy Learning

Page 19

CHAPTER4 Scala Data Types S cala has all the same data types as Java, with the same memory footprint and precision. Following is the table giving details about all the data types available in Scala: Data Type Description Byte 8 bit signed value. Range from -128 to 127 Short 16 bit signed value. Range -32768 to 32767 Int 32 bit signed value. Range -2147483648 to 2147483647 Long 64 bit signed value. -9223372036854775808 to 9223372036854775807 Float 32 bit IEEE 754 single-precision float Double 64 bit IEEE 754 double-precision float Char 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF String A sequence of Chars Boolean Either the literal true or the literal false Unit Corresponds to no value Null null or empty reference Nothing The subtype of every other type; includes no values Any The supertype of any type; any object is of type Any AnyRef The supertype of any reference type All the data types listed above are objects. There are no primitive types like in Java. This means that you can call methods on an Int, Long, etc. Scala Basic Literals: The rules Scala uses for literals are simple and intuitive. This section explains all basic Scala Literals. TUTORIALS POINT Simply Easy Learning

Page 20

INTEGER LITERALS Integer literals are usually of type Int, or of type Long when followed by a L or l suffix. Here are some integer literals: 0 035 21 0xFFFFFFFF 0777L FLOATING POINT LITERALS Floating point literals are of type Float when followed by a floating point type suffix F or f, and are of type Double otherwise. Here are some floating point literals: 0.0 1e30f 3.14159f 1.0e100 .1 BOOLEAN LITERALS The boolean literals true and false are members of type Boolean. SYMBOL LITERALS A symbol literal 'x is a shorthand for the expression scala.Symbol("x"). Symbol is a case class, which is defined as follows. package scala final case class Symbol private (name: String) { override def toString: String = "'" + name } CHARACTER LITERALS A character literal is a single character enclosed in quotes. The character is either a printable unicode character or is described by an escape sequence. Here are some character literals: 'a' '\u0041' '\n' '\t' STRING LITERALS A string literal is a sequence of characters in double quotes. The characters are either printable unicode character or are described by escape sequences. Here are some string literals: "Hello,\nWorld!" "This string contains a \" character." MULTI-LINE STRINGS A multi-line string literal is a sequence of characters enclosed in triple quotes """ ... """. The sequence of characters is arbitrary, except that it may contain three or more consuctive quote characters only at the very end. TUTORIALS POINT Simply Easy Learning

Showing the first 20 pages. Download the document to see it all.

Comments (0)

Sign in to join the discussion

No comments yet. Be the first!