Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use...

132
Pragmatic Jonas Bonér Real-World Scala Scalable Solutions Copyright 2009 Scalable Solutions

Transcript of Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use...

Page 1: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Pragmatic

Jonas Bonér

Real-World Scala

Scalable Solutions

Copyright 2009 Scalable Solutions

Page 2: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

If I were to pick a language to use today other than Java, it would be Scala

James Gosling

Page 3: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Chat app in LiftBuild a multi-user, comet-based chat app

About 30 lines of code

Three slides worth

Slides By David Pollak, creator of Lift

Page 4: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Define Messagescase class Add(who: Actor)

case class Remove(who: Actor)

case class Messages(msgs: List[String])

Page 5: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Chat Server object ChatServer extends Actor { private var listeners: List[Actor] = Nil private var msgs: List[String] = Nil def act = loop { react { case s: String => msgs = s :: msgs listeners.foreach(l => l ! Messages(msgs)) case Add(who) => listeners = who :: listeners who ! Messages(msgs) case Remove(who) => listeners -= who } } this.start}

Page 6: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Chat Comet Component class Chat extends CometActor {

private var msgs: List[String] = Nil def render = <div> <ul>{ msgs.reverse.map(m => <li>{ m }</li>) }</ul> { ajaxText("", s => { ChatServer ! s; Noop }) } </div> override def localSetup = ChatServer ! Add(this) override def localShutdown = ChatServer ! Remove(this) override def lowPriority = { case Messages(m) => msgs = m; reRender(false) }}

Page 7: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Demo

Page 8: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Scalable language

Page 9: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Unique and elegant blend of

OO FP+

Page 10: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Martin Odersky

Since 2001Sponsored by EPFL

Friendly and supportive

community

Runs on the JVM

Production ready

Statically typed

Seamless Java interoperability

Pragmatic

Page 11: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Unique and elegant blend of

is...

Page 12: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val phonebook = Map( “Jonas” -> “123456”, “Sara” -> “654321”)phonebook += (“Jacob” -> “987654”)println(phonebook(“Jonas”))

Expressive & light-weight

Page 13: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

High-level

boolean hasUpperCase = false;for (int i = 0; i < name.length(); i++) { if (Character.isUpperCase(name.charAt(i))) { hasUpperCase = true; break; }}

Java version

Page 14: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

High-level

val hasUpperCase = name.exists(_.isUpperCase)

Scala version

Page 15: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

// Javapublic class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(age: int) { this.age = age; }}

Concise

// Scalaclass Person( var name: String, var age: Int)

Page 16: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Pure OO1 + 21.+(2)

123.toString()

Page 17: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Extensibleval service = actor { loop { receive { case Add(x,y) => reply(x+y) case Sub(x,y) => reply(x-y) } }}service ! Add(4, 2) 6

Page 18: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Pragmaticdef users = <users> <user role=”customer”> <name>{ user.name }</name> <password>{ user.password }</password> <email>{ user.email }</email> </user> ... </users>

Page 19: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Pragmatic

users match { case <users>{users @ _*}</users> => for (user <- users) println(“User “ + (user \ “name”).text)}

Page 20: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

“direct:a“ ==> { loadbalance roundrobin { to (“mock:a“) to (“mock:b“) to (“mock:c“) }}

Great for DSLsApache Camel

Page 21: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Scala isdeep

Page 22: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

But you don't need to go very deep

to still have fun and be productive

Page 23: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Java

Page 24: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tastier Java

Page 25: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Different beast

Page 26: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Composition

Page 27: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

in largeComposition

Page 28: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

building blocks

2

Page 29: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

TraitsSelf-type

&&

annotations

Page 30: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Traittrait Dad { private var children: List[Child] = Nil

def addChild(child: Child) = children = child :: children

def getChildren = children.clone}

Page 31: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Base

class Man(val name: String) extends Human

Page 32: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Plumbing

Page 33: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Static mixin composition

class Man(val name: String) extends Human with Dad

Page 34: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Static mixin compositionusage

class Man(val name: String) extends Human with Dad

val jonas = new Man(“Jonas”)

)

jonas.addChild(new Child(“Jacob”))

Page 35: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Dynamic mixin composition

val jonas = new Man(“Jonas”) with Dad

Page 36: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

jonas.addChild(new Child(“Jacob”))

Dynamic mixin compositionusage

val jonas = new Man(“Jonas”) with Dad

Page 37: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

3 different type of traits

Page 38: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

1

Page 39: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Rich interfacetrait RichIterable[A] { def iterator: Iterator[A] // contract method

def foreach(f: A => Unit) = { val iter = iterator while (iter.hasNext) f(iter.next) }

def foldLeft[B](seed: B)(f: (B, A) => B) = { var result = seed foreach(e => result = f(result, e)) result }}

Page 40: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val richSet = new java.util.HashSet[Int] with RichIterable[Int]

richSet.add(1)richSet.add(2)

richSet.foldLeft(0)((x, y) => x + y) 3

Rich interface

Page 41: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

2

Page 42: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

trait IgnoreCaseSet extends java.util.Set[String] {

abstract override def add(e: String) = { super.add(e.toLowerCase) } abstract override def contains(e: String) = { super.contains(e.toLowerCase) } abstract override def remove(e: String) = { super.remove(e.toLowerCase) }}

Stackable modifications

Page 43: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val set = new java.util.HashSet[String] with IgnoreCaseSet

set.add(“HI THERE“) // uppercase

set.contains(“hi there“) // lowercase true

Stackable modifications

Page 44: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

trait LoggableSet extends java.util.Set[String] {

abstract override def add(e: String) = { println(“Add :“ + e) super.add(e) }

abstract override def remove(e: String) = { println(“Remove :“ + e) super.remove(e) }}

Add another trait interceptor

Page 45: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val set = new java.util.HashSet[String] with IgnoreCaseSet with LoggableSet

set.add(“HI THERE“) “Add: HI THERE”

Run the stack of interceptors

Prints in uppercase

Page 46: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val set = new java.util.HashSet[String] with LoggableSet with IgnoreCaseSet

set.add(“HI THERE“) “Add: hi there”

Change the order

Prints in lowercase

Page 47: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

3

Page 48: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Trait Trait

Trait Trait

Trait

Multiple views

Base

Page 49: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Trait Trait

Trait Trait

Trait

Base

Multiple views

Page 50: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Traits

Multiplepersonalities

Page 51: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Traits

Multiple

facets

Page 52: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

class Order(val cust: Customer)

Base

Page 53: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Facetstrait Entity { ... }trait InventoryItemSet { ... }trait Invoicable { ... }trait PurchaseLimiter { ... }trait MailNotifier { ... }trait ACL { ... }trait Versioned { ... }trait Transactional { ... }

Page 54: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val order = new Order(customer) with Entity with InventoryItemSet with Invoicable with PurchaseLimiter with MailNotifier with ACL with Versioned with Transactional

Composition

Page 55: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Modules / Namespaces

Page 56: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

object Module { ...}

...are effectively singletons

Modules

Page 57: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

object Persistence extends Layer with UserRepository with CartRepository ...

...can be composed of traits

Modulestrait UserRepository { ... } trait CartRepository { ... }

Page 58: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

trait UserRepositoryComponent { val userRepository = new UserRepository class UserRepository { ... }}

Glue it together

trait UserServiceComponent { val userService = new UserService class UserService { def authenticate(name: String, pwd: String) = userRepository.authenticate(name, pwd) }}}

Page 59: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

What do we

need?

Page 60: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

We need the

userRepository

userRepository.authenticate(name, pwd)

Page 61: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

DI

Page 62: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

this: <deps> =>

Page 63: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Dependency declarationtrait UserService { this: UserRepository => ... // provided with composition userRepository.merge(user)}

...using self-type annotation

Page 64: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a
Page 65: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Duck typing

Page 66: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

if it walks like a duck

and talks like a duck

then it's a duckDuck typing

Page 67: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

def authorize(target: { def getACL: ACL }) = { val acl = target.getACL ... //authorize}

Structural Typing: Duck-typing done right

Statically enforced

Page 68: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

in small

Composition

Page 69: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

“It's Time to Get Good at Functional Programming” Dr Dobb's Journal Issue December 2008

Page 70: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

What'sall the

buzzabout?

Page 71: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

FPOrthogonal

Declarative

ReusableDeterministic

High-level

Referentiallytransparent

Immutable

Page 72: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

FP is like

Lego

Page 73: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Small reusable pieces

with input

and output

Page 74: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Unix pipes

cat File | grep 'println' | wc

Page 75: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

(x: Int) => x + 1

Functions

Page 76: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Functions as valuesval inc = (x: Int) => x + 1

inc(1) 2

Page 77: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Functions as parametershigh-order

List(1, 2, 3).map((x: Int) => x + 1) List(2, 3, 4)

Page 78: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Functions as parameterswith sugar

List(1, 2, 3).map((x: Int) => x + 1)

List(1, 2, 3).map(x => x + 1)

List(1, 2, 3).map(_ + 1)

Page 79: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Functions as closures

val addMore = (x: Int) => x + more

Page 80: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

What is more?

Page 81: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

A free variable outsidethe function's lexical scopevar more = 7val addMore = (x: Int) => x + more

addMore(3) 10more = 8addMore(3) 11

Page 82: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Partial application Currying

val add = (x: Int, y: Int) => x + y

val add2 = add(2, _: Int)

add2(3) 5

Page 83: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Data StructuresFunctional

Page 84: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Immutable

Page 85: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Recursive

Page 86: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

ListThe almighty

Page 87: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

ListsGrow at the frontInsert at front O(1)Insert at end O(n)

Page 88: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

List creation

List(1, 2, 3)

1 :: 2 :: 3 :: Nil

Page 89: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Basicsval list = List(1, 2, 3)list.head 1list.tail List(2, 3)

list.isEmpty false

Page 90: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

High-level operationsval list = List(1, 2, 3)list.map(_ + 1) List(2, 3, 4)list.filter(_ < 2) List(1)list.exists(_ == 3) truelist.drop(2) List(3)list.reverse List(3, 2, 1)list.sort(_ > _) List(3, 2, 1)List.flatten(list) List(1, 2, 3)list.slice(2, 3) List(3)...

Page 91: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

115functions defined on List

Page 92: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tuplesdef getNameAndAge: Tuple2[String, Int] = { val name = ... val age = ... (name, age)}

val (name, age) = getNameAndAgeprintln(“Name: “ + name)println(“Age: “ + age)

Page 93: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Otherfunctional data structures:

SetsTreesStacks

Page 94: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

for (n <- names) println(n)

for comprehensions

Page 95: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

for { att <- attendees if att.name == “Fred” lang <- att.spokenLanguages if lang == “Danish” } println(att)

Like SQL queries

Find all attendees named Fred that speaks Danish

Page 96: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val companiesForAttendeesFromLondon = for { att <- attendees if att.address.city == “London” } yield att.company

for / yield

Page 97: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

for (thing <- thingsFromHere) yield getRealThing(thing)

Everything returns a value

Page 98: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val things = for (thing <- thingsFromHere) yield getRealThing(thing)

Everything returns a value

Page 99: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

if (fromHere) { for (thing <- thingsFromHere) yield getRealThing(thing) } else { ffor (thing <- thingsFromThere) yield thing }

Everything returns a value

Page 100: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val things = if (fromHere) { for (thing <- thingsFromHere) yield getRealThing(thing) } else { ffor (thing <- thingsFromThere) yield thing }

Everything returns a value

Page 101: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

try { if (fromHere) { for (thing <- thingsFromHere) yield getRealThing(thing) } else { ffor (thing <- thingsFromThere) yield thing } } catch { case e => error(e); Nil }

Everything returns a value

Page 102: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

val things = try { if (fromHere) { for (thing <- thingsFromHere) yield getRealThing(thing) } else { ffor (thing <- thingsFromThere) yield thing } } catch { case e => error(e); Nil }

Everything returns a value

Page 103: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

def getThingsFromSomewhere( fromHere: Boolean): List[Thing] = { try { if (fromHere) { for (thing <- thingsFromHere) yield getRealThing(thing) } else { ffor (thing <- thingsFromThere) yield thing } } catch { case e => error(e); Nil }}

Everything returns a value

Page 104: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Patternmatching

Page 105: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

def matchAny(a: Any): Any = a match { case 1 => “one” case “two” => 2 case i: Int => “scala.Int” case <tag>{ t }</tag> => t case head :: tail => head case _ => “default” }

Pattern matching

Page 106: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

// compiler adds: toString(), hashCode(), // equals() + companion object with apply()sealed abstract case class Mancase class Bill(age: Int) extends Man case class Ben(age: Int) extends Man

Case classes

val guy = Ben(45)guy match { case Bill(age) => println(“Bill “ + age) case Ben(age) => println(“Ben “ + age)}

Page 107: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Persistence

Page 108: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

JPA@Entity@Inheritance { val strategy = InheritanceType.JOINED }@DiscriminatorColumn { val name = "portfolio_item_type", val discriminatorType = DiscriminatorType.STRING }@serializableclass Portfolio(...) { ...}

Page 109: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

JPA cont.class Portfolio(...) { @Id @GeneratedValue { val strategy = GenerationType.IDENTITY } val id: PortfolioId = _id @ManyToOne @JoinColumn { val name = "strategy_id" } val strategy: Strategy = _strategy

...}

Page 110: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

ConcurrencyImmutability

Actors Message-Passing

STM MVCC

Page 111: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Scala OTPSupervisor hierarchies

All For One One For One

Fault tolerance

Linked actors

Page 112: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tools

Page 113: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tools: scala/binscala

scalacfsc

scaladocsbaz

Page 114: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tools: IDEsEclipse

NetBeansIntelliJ IDEA

EmacsJEdit

Page 115: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tools: Building Maven

AntBuildr

SBT (Simple Build Tool )

Page 116: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Tools: TestingSpecs

ScalaCheckScalaTest

Page 117: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

object stringSpec extends Properties("String") {

specify("startsWith", (a: String, b: String) => (a + b).startsWith(a))

specify("endsWith", (a: String, b: String) => (a + b).endsWith(b)) ...}

ScalaCheck

Page 118: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

object sendSpec extends Spec with JMocker { "A Send service" should { "publish data" in { val mock = mock[Mailer] expect { one(mock).send(any[Mail]) } val sendService = new SendService(mock) sendService.publishData } }}

Specs: mocking

Page 119: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Frameworks: WebLift

SweetSlinkyPinky

Page 120: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

(selected) LibrariesScalaxScalaz

ConfiggyKestrel

Scala OTP

Page 121: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Domain Specific Languages

Page 122: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

// from Apache Camel Scala DSLclass MyRouteBuilder extends RouteBuilder { “direct:a“ --> “mock:a“ “direct:b“ to “mock:b“}

1. Flexible syntax

Page 123: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

// from Apache Camel Scala DSLclass MyRouteBuilder extends RouteBuilder { “direct:a“.-->(“mock:a“) “direct:b“.to(“mock:b“) }

1. Flexible syntax

Page 124: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

// from Apache Camel Scala DSLclass MyRouteBuilder extends RouteBuilder { “direct:a“ --> “mock:a“ “direct:b“ to “mock:b“ }

how can they invoke a method --> on String?

2. Implicits

Page 125: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

implicit def stringToRoute(route: String) = new CamelRoute(str)

class CamelRoute(route: String) { def -->(route: String) = { ... } def to(route: String) = { ... } }

2. Implicits

allows you to define methods on existing classes

Page 126: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

// from Apache Camel Scala DSLclass MyRouteBuilder extends RouteBuilder { (new CamelRoute(“direct:a“)).-->(“mock:a“) (new CamelRoute(“direct:b“)).to(“mock:b“) }

Compiler generation

2. Implicits

Page 127: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

3. Operator overloadingclass CamelRoute(route: String) { ... // unification of two routes def == (route: String): Route = { ... } }

“direct:a“ == “mock:a“

Page 128: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

def myAssert1(predicate: () => Boolean) = if (assertionsEnabled && !predicate()) throw new AssertionError

myAssert1(() => 5 > 3) // ok, but ugly

def myAssert2(predicate: => Boolean) = if (assertionsEnabled && !predicate) throw new AssertionError

myAssert2(5 > 3) // like build into lang

4: Call-by-name

Page 129: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

5. Parser

combinators

Page 130: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Learn morehttp://jonasboner.com

Page 131: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Professional help

http://[email protected]

Consulting Training Mentoring

Page 132: Scalable Solutions · Real-World Scala Scalable Solutions ... If I were to pick a language to use today other than Java, it would be Scala James Gosling. Chat app in Lift Build a

Pragmatic

Jonas Bonér

Real-World Scala

Scalable Solutions

Copyright 2009 Scalable Solutions