Scala - Free

quaggahooliganInternet and Web Development

Feb 5, 2013 (4 years and 9 months ago)

140 views

Model:TPL_Template_of_template_powerpoint

V
1.1

Christophe

Scala

Internal presentation, Valtech

May 2010, the 28
th

Model:TPL_Template_of_template_powerpoint V
1.1

Outline

Introduction


Language overview


Tools


Scala in the enterprise


Conclusion


Model:TPL_Template_of_template_powerpoint V
1.1

INTRODUCTION

Model:TPL_Template_of_template_powerpoint V
1.1

Overview of Scala

Modern multi
-
paradigm programming language designed to
express common programming patterns in a concise, elegant,
and type
-
safe way


Object Oriented (every value is an Object)

Functional (every function is a value)

Statically typed (type inference)

Interoperate with Java (and .NET)

Model:TPL_Template_of_template_powerpoint V
1.1

(Pre)History

Previously: FUNNEL


Minimalist research language based on ‘functional nets”


Not pleasant to use in practice


Scala is designed from
2001
, at EPFL


First public release:
2003


Scala v
2.0
(second, redesigned version):
2006


Today (May,
2010
): v
2.7.7
/ v
2.8


Model:TPL_Template_of_template_powerpoint V
1.1

Licence

SCALA LICENSE


Copyright

(c)

2002
-
2010

EPFL,

Lausanne,

unless

otherwise

specified
.

All

rights

reserved
.

This

software

was

developed

by

the

Programming

Methods

Laboratory

of

the

Swiss

Federal

Institute

of

Technology

(EPFL),

Lausanne,

Switzerland
.

Permission

to

use,

copy,

modify,

and

distribute

this

software

in

source

or

binary

form

for

any

purpose

with

or

without

fee

is

hereby

granted,

provided

that

the

following

conditions

are

met
:

1
.

Redistributions

of

source

code

must

retain

the

above

copyright

notice,

this

list

of

conditions

and

the

following

disclaimer
.

2
.

Redistributions

in

binary

form

must

reproduce

the

above

copyright

notice,

this

list

of

conditions

and

the

following

disclaimer

in

the

documentation

and/or

other

materials

provided

with

the

distribution
.

3
.

Neither

the

name

of

the

EPFL

nor

the

names

of

its

contributors

may

be

used

to

endorse

or

promote

products

derived

from

this

software

without

specific

prior

written

permission
.




THIS

SOFTWARE

IS

PROVIDED

BY

THE

REGENTS

AND

CONTRIBUTORS

``AS

IS''

AND

ANY

EXPRESS

OR

IMPLIED

WARRANTIES,

INCLUDING,

BUT

NOT

LIMITED

TO,

THE

IMPLIED

WARRANTIES

OF

MERCHANTABILITY

AND

FITNESS

FOR

A

PARTICULAR

PURPOSE

ARE

DISCLAIMED
.

IN

NO

EVENT

SHALL

THE

REGENTS

OR

CONTRIBUTORS

BE

LIABLE

FOR

ANY

DIRECT,

INDIRECT,

INCIDENTAL,

SPECIAL,

EXEMPLARY,

OR

CONSEQUENTIAL

DAMAGES

(INCLUDING,

BUT

NOT

LIMITED

TO,

PROCUREMENT

OF

SUBSTITUTE

GOODS

OR

SERVICES
;

LOSS

OF

USE,

DATA,

OR

PROFITS
;

OR

BUSINESS

INTERRUPTION)

HOWEVER

CAUSED

AND

ON

ANY

THEORY

OF

LIABILITY,

WHETHER

IN

CONTRACT,

STRICT

LIABILITY,

OR

TORT

(INCLUDING

NEGLIGENCE

OR

OTHERWISE)

ARISING

IN

ANY

WAY

OUT

OF

THE

USE

OF

THIS

SOFTWARE,

EVEN

IF

ADVISED

OF

THE

POSSIBILITY

OF

SUCH

DAMAGE
.

Model:TPL_Template_of_template_powerpoint V
1.1

LANGUAGE OVERVIEW

for Java developers…

Model:TPL_Template_of_template_powerpoint V
1.1

Hello World !

Easy to understand…


No surprise


“main” is the entry point


“println” writes on stdout




Compilation:

scalac HelloWorld.scala

Execution:

scala
-
classpath . HelloWorld

object
HelloWorld

{


def
main
(
args
: Array[String]) {


println
("Hello, world!")


}

}

Model:TPL_Template_of_template_powerpoint V
1.1

Interaction with Java

Can use Java classes


… and libraries


Import:


Multiple with “{ }”


“_” instead of “*”



Constructor / methods invocation:

df

format now
or

df.format
(now)

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
)


}

}

Model:TPL_Template_of_template_powerpoint V
1.1

Everything is an object (
1
/
2
)

Model:TPL_Template_of_template_powerpoint V
1.1

Everything is an object (2/2)

scala.Any: root

scala.AnyVal vs. scala.AnyRef: two different class worlds


scala.AnyVal


Predifined


Like primitive types (java int, long, char, …)


Views

between some of these classes


scala.AnyRef


All other classes


Correspond to java.lang.Object (in java environment)

User defined classes (in scala):


Always subclass scala.AnyRef


Implicity extends the
trait

scala.ScalaObject

Classes of the infrastructure (java environment)


Not extend scala.ScalaObject

Model:TPL_Template_of_template_powerpoint V
1.1

Traits

Looks like Java interface



Looks like Java abstract class


Can contain implementation


Can’t be instanciated




Allows multiple inheritance…


trait
Runnable

{


def run(): unit;

}

trait
Runnable

{


def

run
(
obj
:
AnyRef
) : unit;


def

run
() : unit = {


System.out.println("...");


run
(
null
);


}

}

class
Foo

extends

Runnable

with

AnotherTrait

{...}

Model:TPL_Template_of_template_powerpoint V
1.1

Views

Implicit conversions


Views are applied in two
situations:


expression e of type T

T does not conform to the
expression's expected type


selection e.m with e of type T

if the selector m does not
denote a member of T

class
UpperString
(s: String) {


override

def

toString
() =
s.toUpperCase

}



def

main(
args
:
Array
[String]) {


implicit

def

stringWrapper
(s: String) =


new
UpperString
(s)


treatUpperString
("toto")

}


def

treatUpperString
(s:
UpperString
) {


// do
something


println
(s)

}

Model:TPL_Template_of_template_powerpoint V
1.1

Functions

Functions are objects:

can be passed as argument







Can be anonymous




Can be nested

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
)

}

def

main(
args
:
Array
[String]) {


oncePerSecond
(() =>
println
("...")
)

}

def

main(
args
:
Array
[String]) {


def

myNestedFunction
() {


println
("...")


}


oncePerSecond
(
myNestedFunction
)

}

Model:TPL_Template_of_template_powerpoint V
1.1

Pattern matching

Built
-
in mechanism


“first
-
match” policy



Match any sort of data


def
matchTest
(x:
Int
): String = x match {


case 0 => "zero"


case 1 => "one"


case _ => "many"

}

def matchTest
2
(x: Any): Any = x match {


case
1
=> "one"


case "two" =>
2


case y:
Int

=> "
scala.Int
"

}

Model:TPL_Template_of_template_powerpoint V
1.1

Exception management

Very closed to java


Try


Catch


Some differences


Catch clause: pattern match


Not mandatory in signature


Java exceptions can be raised

def
matchTest
(x: Any): Any = x match {


case 1 => "one"


case "two" => 2


case y:
Int

=> "
scala.Int
"


case "
doNPE
" =>
null.toString


case "
doIOE
" =>
throw
new
IOException

}


def
doSomething
(x: Any) {


try

{


println
(
matchTest
("
doIOException
"))


}
catch
{


case ex:
scala.MatchError

=>

println
("handle N/A value")


case ex:
NullPointerException

=>

println
("handle NPE")


case ex:
java.io.IOException

=>

println
("handle IOE")


}

}

Model:TPL_Template_of_template_powerpoint V
1.1

Case classes

Comp. to regular classes:


pattern matching


construct instances without “new”


constructor arguments are
accessible from outside


toString
automatically redefined


equals
automatically redefined


hashCode
automatically
redefined

case class Person(first: String, last:
String)



def main(
args
: Array[String]) {


val

p = Person("X", "B") // no new


println
(p) // print: Person(X,B)


println
(
p.first
) // first accessible





p match {


case Person(x, "B") =>


println
(x + "
familly

is B")


case Person(x, y) =>


println
(x + " is unknown: " + y)


}

}

Model:TPL_Template_of_template_powerpoint V
1.1

XML Processing

Scala ease XML processing

“DOM
-
like” data model

… but can use DOM (with java)

XML can be “mixed” with scala


Deconstructing data with
pattern
-
matching




Easy to load

… and save

def create(s: String) = <node n={s}/>

def add(book: Node,
newE
: Node) =


phonebook

match

{


case <book>{
cs

@ _* }</book> =>


<book>{
cs

}{
newE

}</book>


}

def main(
args
: Array[String]) {


val

newPhoneBook

=


add(
scala.xml.XML.loadFile
(“f.xml"),

<entry>
toto
</entry>);


scala.xml.XML.save
("phone.xml",


newPhoneBook
, "UTF
-
8", true);

}

Model:TPL_Template_of_template_powerpoint V
1.1

Actors and Concurrency

Actors ease concurrency


Mask threads complexity…


Asynchronous messages

(synchronous possible)

How ?


Inherit from Actor


Implement “act()”


“receive”


wait for message in actor’s mailbox


delete this message


corresponding action is executed
(pattern
-
matching)


Send message syntax:

actor ! Msg

case class
Msg

case object
PingMsg

extends
Msg

case object
PongMsg

extends
Msg

case object
StopMsg

extends
Msg

object
pingPongMachina

extends Actor {


def act() {


while (true) {


receive {


case
PingMsg

=>


println
("ping from " + sender)


sender !
PongMsg


case
PongMsg

=>


println
("pong from " + sender)


sender !
PingMsg


case
StopMsg

=>


println
("[Trainer] STOP")


exit()


}


}


}

}

Model:TPL_Template_of_template_powerpoint V
1.1

TOOLS

Model:TPL_Template_of_template_powerpoint V
1.1

Plugins for IDE

Eclipse


http://www.scala
-
ide.org/


Requirements: jdk
1.6
, eclipse
3.5


Maturity:

the best… but medium

Other IDE available


IntelliJ IDEA


Netbeans

Syntax highlighting plugins


Emacs, jEdit, Notepad
-
Plus,
TextMate, SubEthaEdit,
TextWrangler, and so on.


Were made available by a number
of independent contributors to the
Scala project.

Model:TPL_Template_of_template_powerpoint V
1.1

SBT: Simple Build Tool

Aims to do the basics well

Requires JDK
1.5
or later

http://code.google.com/p/simple
-
build
-
tool/



Looks like maven…

but Maven plugin exists for Scala

http://scala
-
tools.org/mvnsites/maven
-
scala
-
plugin/


Features


Configuration done in
Scala



Continuous compilation and
testing with
triggered execution



Supports mixed
Scala
/Java
projects, packages jars, generates
documentation with
scaladoc



Supports testing with
ScalaCheck
,
specs
, and
ScalaTest



Parallel task execution, including
parallel test execution


Dependency management
support: inline declarations,
external
Ivy

or
Maven

configuration files, or manual
management


Model:TPL_Template_of_template_powerpoint V
1.1

Libraries and framework

Scalax (Scala Community Library): develop a general utility
library for the Scala language, as a companion to the standard
library

Scalaz: include general functions that are not currently
available in the core Scala API

Scala/xml

Scala/xml: collection of XML tools for Scala


schema2src is a data binding tool


xquery2src translates XQuery to Scala


xslt2src translates XSLT to Scala


More on:
http://www.scala
-
lang.org/node/1209


Model:TPL_Template_of_template_powerpoint V
1.1

Testing

SUnit…


Fully integrated in scala… but deprecated in scala
2.8


Rehersal: easier
-
to
-
use replacement for SUnit in the standard library.

More sophisticated free testing frameworks


ScalaTest:


Write tests in Scala to test either Scala or Java code


Released under the Apache
2.0
open source license.


ScalaCheck:


Scala implementation of the QuickCheck library for Haskell


Open for improvements and extensions that can ease the task of property
-
based,
randomized testing of Scala programs.


Specs


Behaviour
-
Driven
-
Design framework


Simple and typed language to create specifications


Integration with JUnit

Model:TPL_Template_of_template_powerpoint V
1.1

SCALA

IN THE ENTERPRISE

Model:TPL_Template_of_template_powerpoint V
1.1

Industrial references

Some industrial references on Scala’s Web site


http://www.scala
-
lang.org/node/
1658


~
18
references to industrial use


EDF Trading


Integration with existing ~
300
k lines of java code / since
2008


Twitter


Message queue from Ruby to Scala for performance improvement


Xebia, Xerox, FourSquare, Sony, Siemens, …

Model:TPL_Template_of_template_powerpoint V
1.1

Why using Scala?

(source: Alex Pane, API lead at Twitter)


Fast

Functional

Expressive

Statically typed

Object Oriented

Concurrent



Beautiful… but complex

Features


Java compatibility

Actors (
keeps concurrency simple
)

Immutability (
keeps concurrency predictable
)

Type inference (
keeps code clean
)

First
-
class functions (
keep things flexible
)

Traits (
keep behavior reusable
)

Pattern matching

XML literals and query methods


… and more

Model:TPL_Template_of_template_powerpoint V
1.1

CONCLUSION

Model:TPL_Template_of_template_powerpoint V
1.1

What to think about?

Technically interesting… but complex


Yet another derivation of Java?


Buzz around Scala


Easy to integrate in existing software (Java/.NET)

Low risk for performance


Scala is very well documented (
http://www.scala
-
lang.org
)