ScalaTutorial.pdf

(149 KB) Pobierz
A Scala Tutorial
for Java programmers
Version1.3
January16,2014
Michel Schinz, Philipp
Haller
P ROGRAMMING M ETHODS L ABORATORY
EPFL
S WITZERL AND
1270444351.001.png 1270444351.002.png
2
1
Introduction
This document gives a quick introduction to the Scala language and compiler. It
is intended for people who already have some programming experience and want
an overview of what they can do with Scala. A basic knowledge of object-oriented
programming, especially in Java, is assumed.
2
A first example
As a first example, we will use the standard Hello world program. It is not very fasci-
nating but makes it easy to demonstrate the use of the Scala tools without knowing
too much about the language. Here is how it looks:
object HelloWorld{
def main(args:Array[String]){
println("Hello,world!")
}
}
The structure of this program should be familiar to Java programmers: it consists
of one method called main which takes the command line arguments, an array of
strings, as parameter; the body of this method consists of a single call to the pre-
defined method println with the friendly greeting as argument. The main method
does not return a value (it is a procedure method). Therefore, it is not necessary to
declare a return type.
What is less familiar to Java programmers is the object declaration containing the
main method. Such a declaration introduces what is commonly known as a single-
ton object , that is a class with a single instance. The declaration above thus declares
both a class called HelloWorld and an instance of that class, also called HelloWorld .
This instance is created on demand, the first time it is used.
The astute reader might have noticed that the main method is not declared as static
here. This is because static members (methods or fields) do not exist in Scala. Rather
than defining static members, the Scala programmer declares these members in
singleton objects.
2.1 Compiling the example
To compile the example, we use scalac , the Scala compiler. scalac works like most
compilers: it takes a source file as argument, maybe some options, and produces
one or several object files. The object files it produces are standard Java class files.
If we save the above program in a file called HelloWorld.scala , we can compile
it by issuing the following command (the greater-than sign ‘ > ’ represents the shell
prompt and should not be typed):
2.2Runningtheexample
3
>scalacHelloWorld.scala
This will generate a few class files in the current directory. One of them will be called
HelloWorld. class , and contains a class which can be directly executed using the
scala command, as the following section shows.
2.2 Running the example
Once compiled, a Scala program can be run using the scala command. Its usage is
very similar to the java command used to run Java programs, and accepts the same
options. The above example can be executed using the following command, which
produces the expected output:
>scala-classpath.HelloWorld
Hello,world!
3
Interaction with Java
One of Scala’s strengths is that it makes it very easy to interact with Java code. All
classes from the java.lang package are imported by default, while others need to
be imported explicitly.
Let’s look at an example that demonstrates this. We want to obtain and format the
current date according to the conventions used in a specific country, say France 1 .
Java’s class libraries define powerful utility classes, such as Date and DateFormat .
Since Scala interoperates seemlessly with Java, there is no need to implement equiv-
alent classes in the Scala class library–we can simply import the classes of the cor-
responding Java packages:
import java.util.{Date,Locale}
import java.text.DateFormat
import java.text.DateFormat._
object FrenchDate{
def main(args:Array[String]){
val now= new Date
val df=getDateInstance(LONG,Locale.FRANCE)
println(dfformatnow)
}
}
1 Other regions such as the french speaking part of Switzerland use the same conventions.
1270444351.003.png
 
4
Scala’s import statement looks very similar to Java’s equivalent, however, it is more
powerful. Multiple classes can be imported from the same package by enclosing
them in curly braces as on the first line. Another difference is that when importing
all the names of a package or class, one uses the underscore character ( _ ) instead of
the asterisk ( * ). That’s because the asterisk is a valid Scala identifier (e.g. method
name), as we will see later.
The import statement on the third line therefore imports all members of the DateFormat
class. This makes the static method getDateInstance and the static field LONG di-
rectly visible.
Inside the main method we first create an instance of Java’s Date class which by
default contains the current date. Next, we define a date format using the static
getDateInstance method that we imported previously. Finally, we print the current
date formatted according to the localized DateFormat instance. This last line shows
an interesting property of Scala’s syntax. Methods taking one argument can be used
with an infix syntax. That is, the expression
dfformatnow
is just another, slightly less verbose way of writing the expression
df.format(now)
This might seem like a minor syntactic detail, but it has important consequences,
one of which will be explored in the next section.
To conclude this section about integration with Java, it should be noted that it is also
possible to inherit from Java classes and implement Java interfaces directly in Scala.
4
Everything is an object
Scala is a pure object-oriented language in the sense that everything is an object,
including numbers or functions. It differs from Java in that respect, since Java dis-
tinguishes primitive types (such as boolean and int ) from reference types, and does
not enable one to manipulate functions as values.
4.1 Numbers are objects
Since numbers are objects, they also have methods. And in fact, an arithmetic ex-
pression like the following:
1+2 * 3/x
consists exclusively of method calls, because it is equivalent to the following expres-
sion, as we saw in the previous section:
4.2Functionsareobjects
5
(1).+(((2). * (3))./(x))
This also means that + , * , etc. are valid identifiers in Scala.
The parentheses around the numbers in the second version are necessary because
Scala’s lexer uses a longest match rule for tokens. Therefore, it would break the fol-
lowing expression:
1.+(2)
into the tokens 1. , + , and 2 . The reason that this tokenization is chosen is because 1.
is a longer valid match than 1 . The token 1. is interpreted as the literal 1.0 , making
it a Double rather than an Int . Writing the expression as:
(1).+(2)
prevents 1 from being interpreted as a Double .
4.2 Functions are objects
Perhaps more surprising for the Java programmer, functions are also objects in Scala.
It is therefore possible to pass functions as arguments, to store them in variables,
and to return them from other functions. This ability to manipulate functions as
values is one of the cornerstone of a very interesting programming paradigm called
functional programming .
As a very simple example of why it can be useful to use functions as values, let’s
consider a timer function whose aim is to perform some action every second. How
do we pass it the action to perform? Quite logically, as a function. This very simple
kind of function passing should be familiar to many programmers: it is often used
in user-interface code, to register call-back functions which get called when some
event occurs.
In the following program, the timer function is called oncePerSecond , and it gets
a call-back function as argument. The type of this function is written ()=>Unit
and is the type of all functions which take no arguments and return nothing (the
type Unit is similar to void in C/C++). The main function of this program simply
calls this timer function with a call-back which prints a sentence on the terminal.
In other words, this program endlessly prints the sentence “time flies like an arrow”
every second.
object Timer{
def oncePerSecond(callback:()=>Unit){
while ( true ){callback();Threadsleep1000}
}
def timeFlies(){
println("timeflieslikeanarrow...")
}
Zgłoś jeśli naruszono regulamin