Introduction to Scala

streakconvertingSoftware and s/w Development

Dec 13, 2013 (3 years and 8 months ago)

60 views

Delivering Excellence in Software Engineering

® 2008. EPAM Systems. All rights reserved.


Introduction

to

Scala



® 2008. EPAM Systems. All rights reserved.

Brief

history

of
programming

languages

1801
-

Joseph Marie Jacquard uses punch cards to instruct a loom to weave
"hello, world" into a tapestry.
Redditers

of the time are not impressed due to
the lack of tail call recursion, concurrency, or proper capitalization.

1940s
-

Various "computers" are "programmed" using direct wiring and
switches. Engineers do this in order to avoid the tabs
vs

spaces debate.

1964
-

John
Kemeny

and Thomas Kurtz create BASIC, an unstructured
programming language for non
-
computer scientists.


1965
-

Kemeny

and Kurtz go to 1964.

2003


F
irst

Scala
release

From

http://
james
-
iry.blogspot.com/2009/05/brief
-
incomplete
-
and
-
mostly
-
wrong.html





® 2008. EPAM Systems. All rights reserved.

Introduction

to

Scala

-

Agenda


Intro


Control

structures


Functions


Collections


OO


Implicits


Unit testing


Parting
thoughts



® 2008. EPAM Systems. All rights reserved.

Current state of Scala


Modern
language


OO and FP
concepts

integrated


Run

on

JVM (and
soon

.NET)


By

Martin
Odersky

(
EPFL)


Generic

Java ( =>
generics

in

Java

1.5)


Java
compiler

implementation

(
Java

1.3)


FOSS


Scala
License

~ 3
-
clause BSD
license


Commercial

support

available

(
TypeSafe
)


4

® 2008. EPAM Systems. All rights reserved.

Hands
-
on

experience


Compiled

lang
,
but

we

can

use

REPL


Read
-
Evaluate
-
Print
-
Loop
,
for

experimenting


Execute
:
scala
,
or

go
to

http
://www.simplyscala.com
/



Formatting


® 2008. EPAM Systems. All rights reserved.

Powerful

type

system


Compile
-
time

static

type

checking





Local
type

inference

® 2008. EPAM Systems. All rights reserved.

Variables

and
values


var

and
val


Mutable

vs

immutable


var x = 5

variable
,
mutable

reference

to

x


val

x = 4

value
,
immutable

reference

to

x


Like

final

someType

x

in

Java


Reference

is
immutable
,
but

not

necessary

the

object



May
optionally

specify

type


val

x:
String

= „hello”


Compiler

infers

it

for

us

anyway


Nice

to

specify

type

explicitly

for

public

API

® 2008. EPAM Systems. All rights reserved.

Control

s
tructures

from

http
://xkcd.com/292
/


® 2008. EPAM Systems. All rights reserved.

Control

structures



Sequence

and
branching


Control

structures

as

functions


Sequence


last

statement

(of
block
) is
the

result

of
the

block






Branching


branch

taken

is
the

result



® 2008. EPAM Systems. All rights reserved.

Control

structures



P
attern

matching


Pattern

matching

(
briefly
)


Can

be
simple
, Scala’s
switch






Or

more
comprehensive

(
structural

unification
)

free
variables

guard

expression

default

case

no
fall
-
through

between

cases

® 2008. EPAM Systems. All rights reserved.

Control

structures



L
oops


While

loop


Result

is
Unit

(Scala’s
void
)





For

loop


Swiss

army

knife
,
but

can

be
as

simple

as




® 2008. EPAM Systems. All rights reserved.

For
loop

revisited


For

loop


Can

contain

3
kind

of
clauses


Generators


i <
-

something


Conditions

if

i == 5


Definitions

a = i * 2




Clauses

can

be
on

separate

lines

if

in

curly

braces

® 2008. EPAM Systems. All rights reserved.

For
loop

revisited


For

loop


Ordering

and
composition

of
clauses

not

restricted






Generators

pattern
-
match


Silently

skip

if

match

fails
!

Note
:
these

are

tuples

pattern

® 2008. EPAM Systems. All rights reserved.

For
loop

revisited



For

loop

(
comprehension
)


Can
:


Just

do

some

side
-
effect


Or

create

a
collection

(
yield
)





Under

the

hood


For

comprehension

is
syntactic

sugar


Expands

to

map,
withFilter
,
foreach




yield

must
come

before

the

for

body

® 2008. EPAM Systems. All rights reserved.

Quiz



Control

structure

quiz


Inputs


dest

= List(„HU”, „SP”)


hotelByCountry

= Map(„SP”
-
> 100, „FR”
-
> 80, „HU”
-
> 20)


Help


The
result

of
someMap
(
key
) is
the

respective

value


Output


Sum
number

of
hotels



Example

solution


var s = 0


f
or (c <
-

dest
) s +=
hotelByCountry
(c)


s

® 2008. EPAM Systems. All rights reserved.

Functions

and
methods



Method


Defined

by

a
class
/
object







Shorthand


Return

type

inferred


Still

nice

to

explicitly

write

it

for

public

API

No
need

for

block

for

single

expression

argument

is
val

by

default
,
can
’t
change

® 2008. EPAM Systems. All rights reserved.

Functions

and
methods


Function


Object

by

itself


Has
type



FunctionN
[
-
ArgT1,
-
ArgT2, …,
-
ArgTN
, +
ResT
]


(ArgT1, ArgT2, …,
ArgTN
) =>
ResT


Can

be
passed

as

parameter
, etc.


Ideal

for

callbacks
, etc.


No
need

for

single
-
method

class

boilerplate










Argument

list

Return

value

Type

of
value

May
omit

type

as

usual

® 2008. EPAM Systems. All rights reserved.

Functions

and
methods


Argless

methods









Don’t mind..
Bottom

line is,
can
’t
do

it

Parenless

method

is
called

without

parens

Method

with

paren

may

be
called

either

way
,
but

good

practice

to

stick

to

calling

with

parens
.

® 2008. EPAM Systems. All rights reserved.

Functions

and
methods


Argless

funs









So

f is
the

function

itself

f is a
value
,
containing

a

function

taking

no
args
,
returning

Boolean

Applying

the

function

® 2008. EPAM Systems. All rights reserved.

Functions

and
methods



Procedure


Not

a
third

kind
,
just

naming


Can

be
method

or

function


Return

type

Unit


Only

value

is (),
anything

can

be
converted

to

it

=> no
need

to

write

explicitly


Called

for

its

side
-
effect









No
return

type

or

equals

sign

® 2008. EPAM Systems. All rights reserved.

Functions

and
methods


Method

call

with

named

args





Default

argument

values








® 2008. EPAM Systems. All rights reserved.

Quiz


Function

quiz


Inputs


val

hasFreeRoom

= (c:
String
) => (
c

== „HU”)


val

locations

= „ES” :: „HU” :: „FR” ::
Nil


Write

a
fun

taking

a

function

pred

as

arg


val

filter = (
cs
: List[
String
],
pred
: ???) => ???


filter(
location
,
hasFreeRooms
)
should

return

„HU” ::
Nil



Example

solution


val

filter = (
cs
: List[
String
],
pred
:
(
String
) =>
Boolean
) =>


for (c <
-

cs

if

pred
(
c
))
yield

c



Function

type

deliberately

omitted

for

quiz

® 2008. EPAM Systems. All rights reserved.

Iterators


from

http
://xkcd.com/571/

® 2008. EPAM Systems. All rights reserved.

Collections



Mutable

and
immutable


Packages
:


scala.collection

(
this

has
the

common

interface
)


scala.collection
.{
mutable
,
immutable
}



Modify

ops

on

immutable

collections

result

in

new

collection


Quite

effective
,
not

copy
-
all



Why

immutable
?


No
need

to

be
defensive


No
concurrency

issues


Why

mutable
?


May be
easier

for
some

problems


Possibly

better

performance





Scala
philosophy
:


If

possible
,
have

immutable

interface
,

and
speed

up

internals

with

mutable

solution
.

® 2008. EPAM Systems. All rights reserved.

Collections



Hierarchy

(
subset
)


Traversable


Iterable


Seq

»
IndexedSeq

(
Vector
,
Wrapped
Array
)

»
LinearSeq

(
List
)

»
Buffer

(
ArrayBuffer
,
ListBuffer
)


Set

(
HashSet
,
BitSet
,
SortedSet
, …)


Map (
HashMap
,
SortedMap
, …)

Can

apply

operation

effectively

for

all

elements

in

one

go

Has
iterator

with

hasNext

/
next

Fast

random
access

Fast

linear

access

Italic

style
:
mutable

type

Bold

style
:
immutable

type

® 2008. EPAM Systems. All rights reserved.

Collections


Creating

collections


scala.collection.immutable
._ is
imported

by

default



Can

create

a
default

implementation

using

just

the

type

name


Why
?
See

in

OO part.


Why

is
it

good
?










The
shorthand

form

chooses

an
appropriate

implementation

for

us


In

this

case
, a
special

type

for 1
-
element
maps

(
efficient
)

Ah!
It
’s a
HashMap
!

WTH?

® 2008. EPAM Systems. All rights reserved.

Collections


Type

&
syntax

remarks


Lists




Tuples







Eye

candy

for

TupleX

Alternate

syntax

for

Tuple2

® 2008. EPAM Systems. All rights reserved.

Collections



Rich and
unified

collection

interface


methods

of
collection

classes


map, filter,
foreach
, …





Let
’s stop here
for

a
moment
.
This

is
very

useful
,
but

a bit
many

to

type












Dotless

method

call

Curly

brace

instead

paren
*

*:
matter

of
taste

Let

inferencer

guess

arg

type

Shorthand

syntax

for

anonymous

fun

c.map
(f):
applies

a
function

f
to

all

elements

of
collection

c,
yields

new

collection

® 2008. EPAM Systems. All rights reserved.

Collections


Rich and
unified

collection

interface


Instead

of map, filter, …
return

type

always

being
Iterable


Result

type

is
kept

as

close

to

original

as

possible















Result

is map

Result

is
Iterable

® 2008. EPAM Systems. All rights reserved.

Collections


Rich and
unified

collection

interface


map, filter … and
other

20


30
useful

methods











No
need

to

roll
your

own
,
can

spare

a
lot

of
time


Easy

to

achieve

complex

task

using

composing

these

functionality




® 2008. EPAM Systems. All rights reserved.

Quiz



Collection

quiz


Inputs


dest

= List(„HU”, „SP”)


hotelByCountry

= Map(„SP”
-
> 100, „FR”
-
> 80, „HU”
-
> 20)


Help


Use

the

map
as

a
function
,
then

sum


Output


Sum
number

of
hotels



Example

solutions


dest

map
hotelByCountry

sum


(for (d <
-

dest
)
yield

hotelByCountry
(
d
)) sum

® 2008. EPAM Systems. All rights reserved.

OO


Classes


Syntax


Primary

constructor

as

class

arguments


Body
not

mandatory






Argument

/
member

/
field

modifiers
:


No
modifier

~
val

with

private
[
this
]
visibility
,
no

accessors

(
ctor

only
)


val
/var ~
public

visibility


private
,
private
[…],
protected
,
protected
[…]


Note
: Scala’s
protected

is
not

Java’s
package

protected




® 2008. EPAM Systems. All rights reserved.

OO


Uniform Access


Instead

hidden

val
/var +
getter
/
setter


Can

just

expose

the

val
/var


And
if

needed

later


hide

val
/var


define

accessor

methods





® 2008. EPAM Systems. All rights reserved.

OO


Single

inheritance



Abstract

method

and
class





Method

overriding

® 2008. EPAM Systems. All rights reserved.

OO


Trait

as

interface




Not

so

nice
,
boilerplate

Why

works
?

Can

override

argless

def

with

a
val

(
not

other

way

around
)

But

this

is
also

possible
:

® 2008. EPAM Systems. All rights reserved.

OO


Trait

as

helper

mixin


Either

for
private

or

public

use


Adds

functionality
,
but

does

not

modifies




Abstract

field
,
needs

to

be
specified

when

mixed
in

Added

functionality

Mix
it

in

And
use

® 2008. EPAM Systems. All rights reserved.

OO


Trait

self
-
type


Specifies

the

type

the

trait

needs

to

be mixed
into


This

trait

must be mixed
into

a
Reservable


Use

Reservable

functionality

® 2008. EPAM Systems. All rights reserved.

OO


Trait

as

stackable

modification




Why

not

self
-
type
?

Because

PoliteWisher

is
-
a
W
isher

Linearization

determines

stacking

order

® 2008. EPAM Systems. All rights reserved.

OO


Singletons


object

instead

of
class


Same

name

as

class
/
trait

=> „
companion

object



Frequently
,
companion

as

factory

® 2008. EPAM Systems. All rights reserved.

OO


Case

classes


Ctor

args

become

val
’s
automatically
,
construction

can

omit

new

Example

usage

Singleton

cases
,
enum
-
like

® 2008. EPAM Systems. All rights reserved.

OO


Case

classes


Generated

equals
,
hashCode
,
copy





Supports

easy

pattern

matching









Best
if

immutable
, no
subclasses

c
opy

creates

new

object

with

altered
state

Could

invert

case

order

to

give

Hungary a
leverage

® 2008. EPAM Systems. All rights reserved.

Handling

nulls


Option

type


empty
/1
-
element
collection
,
instead

of null/
value


Chaining
,
pattern

matching


Cases
:
None

or

Some
(x)


Common

operations
:
isDefined
,
getOrElse
,
orElse
, map,
flatMap



Note
!
orElse

takes

a
val

(
calculated

only

once
),

So

in

one

run

we

either

always

lie

or

not

® 2008. EPAM Systems. All rights reserved.

Implicit
conversion


Implicits


Let
’s
magic

happen


Value

defined

as

implicit
gets

passed

to

implicit

argument


Implicit
argument

Btw
,
methods

can

have

multiple

argument

lists

(
currying
,
implicits
,
inference
)

® 2008. EPAM Systems. All rights reserved.

Implicit
conversion


Implicits


Compiler

tries

implicit
conversions

on

failed

method

resolution


® 2008. EPAM Systems. All rights reserved.

Implicit
conversion


Implicits


Conversion

using

src
/
dst

type
’s
companion


® 2008. EPAM Systems. All rights reserved.

Implicit
conversion


Implicits


The
compiler


w
on
’t
chain

implicits

(1
-
step
max
)


won
’t
use

implicit
if

more
than

one

in

scope




unless

it

is
not

ambigous
:


Will

use

implicit
defined

in

nearest

subclass


Will

use

more
special

implicit (
like

Java’s
overload

resolution
)






Famous

implicits
:


Many

in

scala.Predef


scala.collection.JavaConversion
._






Don’t
overuse

implicits
!

And
always

restrict

their

scope
.

® 2008. EPAM Systems. All rights reserved.

Unit testing


ScalaTest


One

possible

choice


Other

famous
:
specs
(2)


Specs

runs

tests

in

isolation


ScalaTest

runs

spec


as

read

by

user

sequentially
,
without

isolation


Many

Spec

styles

supported


FlatSpec
,
WordSpec
,
FeatureSpec
, …


These

differ

in

test
organization

only


Tests

(„
Specs
”)
can

be
read

as

unit
specification


Can

mix
in

matchers
,
informative

elements


ShouldMatchers


Given
-
When
-
Then


Interop


Can

run

via

JUnit

runner


Can

test Java
classes

® 2008. EPAM Systems. All rights reserved.

ScalaTest

-

FlatSpec


® 2008. EPAM Systems. All rights reserved.

ScalaTest

-

FeatureSpec


First

a
rough

outline

® 2008. EPAM Systems. All rights reserved.

ScalaTest

-

FeatureSpec

Refinements

® 2008. EPAM Systems. All rights reserved.

Domain
Specific

Language


Internal

DSLs

® 2008. EPAM Systems. All rights reserved.

Scala
in

the

industry


Pros


Orthogonal

to

maven
/
spring
/
hibernate
/
lucene
/…


Code

coverage

tools

exist

(
scct
,
cobertura
)


Helpful

community

(
scala
-
lang.org
,
stackoverflow
)


Where

to

improve


TypeSafe

now

focuses

on

improving

tooling


Checktyle
,
Eclipse
,
Type

debugger
, …


How

to

use

on

project


Convince

lead /
customer


Introduce

to

Java
projects

gently


For
quick

modeling

of
new

design


For unit
tests


For
isolated

modules


For
example

parser

combinators

for
parsing

custom

DSL

® 2008. EPAM Systems. All rights reserved.

Scala
in

the

industry


image
from

the

slide

of János
Setény

/ Scala Training @ Szeged

?

http://opensource.imageworks.com/?
p=scalamigrations

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


https://vibe.novell.com
/

http://
days2010.scala
-
lang.org/node/138/143

http://
www.web2expo.com/webexsf2009/public
/schedule/detail/6110

http://
days2010.scala
-
lang.org/node/138/159

® 2008. EPAM Systems. All rights reserved.

What
’s
next
?


Not

covered
,
but

worth

reading


Generic

types


Pass

by

name


Lazy

values


IO,
Source


XML


Parser

combinators


Actor

framework


Style

guide




® 2008. EPAM Systems. All rights reserved.

Recap


Take
-
home


Immutability

helps

(ok
to

share
)


Transform

instead

of
mutating

if

you

can


If

you

use

mutable

state
,
try

to

hide

it


Option

types

to

fight

nulls


Multiple

behavior

inheritance

safe

via

linearization


Don’t
forget

to

write

clean

code


Relax

and
enjoy

life


Automatic

type

inference


Rich
collections


Sunset


® 2008. EPAM Systems. All rights reserved.

That
’s for
now


® 2008. EPAM Systems. All rights reserved.

Resources


Books


http
://ofps.oreilly.com/titles/9780596155957
/

-

Free
book


http://
www.artima.com/shop/programming_in_scala

-

Authors
’ Scala
book



Interesting

to

read

/
hear


http
://
www.artima.com/scalazine/articles/origins_of_scala.html


(
origins
)


http
://www.se
-
radio.net/2011/02/episode
-
171
-
scala
-
update
-
with
-
martin
-
odersky
/


(
current

state

of Scala
podcast
)


http
://days2011.scala
-
lang.org/
sites
/days2011/
files
/01.%
20Martin%20Odersky.pdf


(
state

of Scala
talk

slides
)


http
://
stackoverflow.com/questions/1332574/common
-
programming
-
mistakes
-
for
-
scala
-
developers
-
to
-
avoid

(and
generally

scala

on

SO)


http://
scala.wikispaces.com/Libraries

(
set

of
scala
-
related

libraries
)




Delivering Excellence in Software Engineering

® 2008. EPAM Systems. All rights reserved.


Questions?

For more information, please contact:


Robin Palotai

Robin_Palotai
@epam.com

/
palotai.robin
@
gmail.com


EPAM Systems

http://www.epam.com