Вы находитесь на странице: 1из 12

Scala

Java
1.3
10, 2010

Michel Schinz,
Philipp Haller,
(.)

PROGRAMMING METHODS LABORATORY


EPFL
SWITZERLAND

1

Scala. ,
, Scala.
- ,
Java.

2
Hello world.
,
Scala . :
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!" )
}
}
Java-:
main , , ;
println
. main (
).
.
Java - object, main
.
singleton , . ,
HelloWorld
HelloWorld. (on
demand), .
, main static.
static- ( ) Scala.
( ) Scala
singleton .

2.1
, scalac, Scala. scalac
: ,
, . ,
- java .
HelloWorld.scala,
e ( > --
, ):
> scalac HelloWorld.scala
class .
HelloWorld.class ,

scala, .
2.2
Scala
scala. java java
.
, :
> scala -classpath . HelloWorld
Hello, world!

3 Java
Scala Java.
java.lang ,
.
, .

, 1.
Java , Date
DateFormat. Scala Java,
Scala -
Java :
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(df format now)
}
}
Sala Java ,
. ,
, . -
, (_)
(*). - Scala
(, ), .
,
DateFormat. getDateInstance LONG
.
main Java- Date,
. ,
getDateInstance , . , ,
,
1 , ,
.

DateFormat .
Scala. , ,
. :
df format now
,
df.format(now)
,
.
Java,
Java Java Scala.

4
Scala - - ,
, . Java .. Java
( boolean int) ,
.

4.1
.. , . ,
:
1+2*3/x
, (
) :
(1).+(((2).*(3))./(x))
+, *, .. Scala.
, Scala
.
:
1.+(2)
1., +, 2. , , 1.
, 1. 1.
1.0, Double Int. :
(1).+(2)
1 1 Double.

4.2 .
Java ,
Scala. ,
.
-
, .

,
,
. ? ,
.
: (UI),
(call back), ,
.
, oncePerSecond,
call-back . () => Unit
( Unit
void C/C++). main callback , . ,
time ies like an arrow.
object Timer {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def timeFlies() {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
oncePerSecond(timeFlies)
}
}
,
println , System.out.

4.2.1
, .
, timeFlies ,
oncePerSecond. ,
, , , ,
, oncePerSecond. Scala
,
. -,
timeFlies, :
object TimerAnonymous {
def oncePerSecond(callback: () => Unit) {
while (true) { callback(); Thread sleep 1000 }
}
def main(args: Array[String]) {
oncePerSecond(() =>
println("time flies like an arrow..."))
}
}

=> , .
, .
, timeFlies, .

5
, Scala - , ,
2. Scala
Java. , Scala ,
:
class Complex(real: Double, imaginary: Double) {
def re() = real
def im() = imaginary
}
complex ,
. ,
Complex, : new Complex(1.5, 2.3). ,
re im, .
, .
,
, Double.
, , , ,
, , .
, ,
, . , Scala
,
, .
,
, .

5.1
re im , , ,
, .
object ComplexNumbers {
def main(args: Array[String]) {
val c = new Complex(1.2, 3.4)
println("imaginary part: " + c.im())
}
}
real imaginary
, .
Scala, .
,
, . Complex
:
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
}

2 , , -
, Scala -

5.2
Scala . ,
Complex , scala.AnyRef.
, Scala.
, , , override
, , . ,
Complex toString,
Object.
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "I"
}

6 Case - .
.
; XML
- ;
- .
Scala
. -
,
. : 1+2 (x + x) + (7 + y).
. , ( ) (
).
Java ,
.
.
Scala case-. - .

:
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(n: String) extends Tree
case class Const(v: Int) extends Tree
Sum, Var Const case-
:
new (
Const(5) new Const(5)),
getter (
v c
Const c.v),
equals hashCode,
,
toString
" " ( x+1
Sum(Var(x),Const(1)))

,
.
.
- . x+1
5 x, {x 5},
6.
.
,
!
, (). {x 5}
Scala:
{ case "x" => 5 }
, "x"
5, .
.
String => Int ,
. Scala :
type Environment = String => Int
Environment
String Int.
.
: ;
; -
. Scala :
def eval(t: Tree, env: Environment): Int = t match {
case Sum(l, r) => eval(l, env) + eval(r, env)
case Var(n) => env(n)
case Const(v) => v
}
(pattern matching )
t. :
1. - , -
l - r
; ( )
. .. l r .
, .. ,
Var; , Var n
.
, .. t Sum Var,
Const, ,
Const v .
,
.
Tree.
2. -
, ,
,


-
eval Tree .
Scala case-
. - ,
:
..
Tree;
, ..
Tree,
:

, ; ,
, .

: .
:
1.
2. v v -
, .
3. .
Scala ,
:
def derive(t: Tree, v: String): Tree = t match {
case Sum(l, r) => Sum(derive(l, v), derive(r, v))
case Var(n) if (v == n) => Const(1)
case _ => Const(0)
}
. -
case- ,
if.
true.
1
v.
- , _,
, .
, ,
.
.
main , (x
+ x) + (7 + y): {x 5, y 7},
.
def main(args: Array[String]) {
val exp: Tree = Sum(Sum(Var("x"),Var("x")),Sum(Const(7),Var("y")))
val env: Environment = { case "x" => 5 case "y" => 7 }
println("Expression: " + exp)
println("Evaluation with x=5, y=7: " + eval(exp, env))
println("Derivative relative to x:\n " + derive(exp, "x"))
println("Derivative relative to y:\n " + derive(exp, "y"))
}

, :
Expression: Sum(Sum(Var(x),Var(x)),Sum(Const(7),Var(y)))
Evaluation with x=5, y=7: 24
Derivative relative to x:
Sum(Sum(Const(1),Const(1)),Sum(Const(0),Const(0)))
Derivative relative to y:
Sum(Sum(Const(0),Const(0)),Sum(Const(0),Const(1)))
() ,
, .
- ( ) ,
.

7
, Scala
.
Java
, . Scala
,
.
, :
.
, . Java,
Comparable . Scala
Java, Comparable ,
Ord.
, 6 : ,
, , , , .
, .
( ) , . Scala
:
trait Ord{
def < (that:Any):Boolean
def<=(that:Any):Boolean = (this < that) || (this == that)
def> (that:Any):Boolean = !(this <= that)
def>=(that:Any):Boolean = !(this < that)
}
Ord, Java Comparable
,
. ..
.
Any - ,
Scala. Object
Java, .. Int, Float, . .
, ,


Ord . , Date
. ,
, . , :
class Date(y: Int, m: Int, d: Int) extends Ord {
def year = y
def month = m
def day = d
override def toString(): String = year + "-" + month + "-" + day
- extends Ord,
. Date Ord.
equals, Object, ,
.
equals , .
:
override def equals(that: Any): Boolean =
that.isInstanceOf[Date] && {
val o = that.asInstanceOf[Date]
o.day == day && o.month == month && o.year == year
}
isInstanceOf asInstanceOf.
, isInstanceOf, Java's instanceof true ,
, , .

asInstanceOf Java:
, , ClassCastException.
,
"". , error,
.
def <(that: Any): Boolean = {
if (!that.isInstanceOf[Date])
error("cannot compare " + that + " and a Date")
val o = that.asInstanceOf[Date]
(year < o.year) ||
(year == o.year && (month < o.month ||
(month == o.month && day < o.day)))
}
Date.
. ,
: equals <
Date, Ord.
, ,
.

8 (Genericity)
scala - .
Java in Java 1.5.

- ,.,

. ..
, ,
Int. .
Java Object, .
, , .. / (int,long,
float, ..) ,
.
Scala ( )
.
: , -
.
class Reference[T] {
private var contents: T = _
def set(value: T) { contents = value }
def get: T = contents
}
Reference , T, .
, set ,
get .
Scala,
. , ,
_, . 0
, false Boolean , () Unit null
.
Reference ,
T, Reference.
Reference :
object IntegerReference {
def main(args: Array[String]) {
val cell = new Reference[Int]
cell.set(13)
println("Reference contains the half of " + (cell.get * 2))
}
}
,
get Integer.
- , ..
.

9
Scala .

Scala By Example, ,
Scala Language Specication .