all about scala

99
1 Created on 10/01/2012 of 99 Yardena Meymann January 10, 2012 http ://www.meetup.com/ILTechTalks/ ALL* ABOUT SCALA *ALL I COULD FIT IN 90 MINUTES PRESENTATION, IN FACT THERE IS MUCH MORE TO SCALA…

Upload: yardena-meymann

Post on 28-Jan-2015

113 views

Category:

Technology


0 download

DESCRIPTION

ILTechTalk presentation

TRANSCRIPT

Page 1: All about scala

1 Created on 10/01/2012 of 99

Yardena MeymannJanuary 10, 2012http://www.meetup.com/ILTechTalks/

ALL* ABOUT SCALA *ALL I COULD FIT IN 90 MINUTES PRESENTATION,

IN FACT THERE IS MUCH MORE TO SCALA…

Page 2: All about scala

2 Created on 10/01/2012 of 99

NAVIGATION

– Background

– Scala basics

– OOP in Scala

– FP in Scala

– Concurrency

– Tools

– Resources

Page 3: All about scala

3 Created on 10/01/2012 of 99

IT DOES NOT HAVE TO BE JAVA

it is tastier when you mix them!

Java

Java Compiler

Bytecode

Java Virtual MachineCA FE

BA BE

Scala

Scala Compiler

Bytecode

Groovy

Groovy Compiler

Bytecode

Page 4: All about scala

4 Created on 10/01/2012 of 99

WHAT IS SCALA

– Object oriented and functional

– Statically typed - advanced type system

– Compiled to JVM bytecode but also to CLR, and to JavaScript (in progress);

works with Dalvik

– High performance

– Very good interoperability with Java

– Support for modularity and extensibilityDSL friendly

Page 5: All about scala

5 Created on 10/01/2012 of 99

JAVA AND SCALA TIMELINE

lawsuit 2001

2.9 2011 2.3 2007

2.7 2008 2.8 2010

2009

€2.3 million 2011 2011

Java 7 (Dolphin)

2011

Page 6: All about scala

6 Created on 10/01/2012 of 99

THEN AND NOW

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

James Gosling

Page 7: All about scala

7 Created on 10/01/2012 of 99

TOOLS

– IDE: • built-in REPL, Scala IDE (based on Eclipse), IntelliJ and NetBeans plug-ins, ENSIME

– Tools• https://wiki.scala-lang.org/display/SW/Tools+and+Libraries

• integration modules for almost every popular Java framework

scala>

Page 8: All about scala

8 Created on 10/01/2012 of 99

OPEN SOURCE

Page 9: All about scala

9 Created on 10/01/2012 of 99

INDUSTRY

Page 10: All about scala

10 Created on 10/01/2012 of 99

BOOKS

Page 11: All about scala

11 Created on 10/01/2012 of 99

JOBS

Page 12: All about scala

12 Created on 10/01/2012 of 99

TYPESAFE

Page 13: All about scala

13 Created on 10/01/2012 of 99

HELLO SCALA!

Let’s see some code now…

Page 14: All about scala

14 Created on 10/01/2012 of 99

HELLO SCALA

Page 15: All about scala

15 Created on 10/01/2012 of 99

SCALA REPL

Page 16: All about scala

16 Created on 10/01/2012 of 99

HELLO SCALA

package com.hp.scala

object HelloScala {

def main(args: Array[String]) {

println(“Hello Scala”)

}

}

package com.hp.scala;

public class object HelloScala {

public static void def main(String[] args: Array[String]) {

System.out.println(“Hello Scala”);

}

}

Page 17: All about scala

17 Created on 10/01/2012 of 99

HELLO SCALA - VARIABLES

object HelloScala {

def main(args: Array[String]) {

val msg = “Hello Scala”

println(msg)

}

}

Page 18: All about scala

18 Created on 10/01/2012 of 99

HELLO SCALA – TYPE INFERENCE

object HelloScala { def main(args: Array[String]) {

val msg = “Hello Scala”println(msg)

}}

Page 19: All about scala

19 Created on 10/01/2012 of 99

VAL VS. VAR

object HelloScala {

def main(args: Array[String]) {

val msg = “Hello Scala”

println(msg)

msg = “Goodbye Java”

println(msg)

}

}

Page 20: All about scala

20 Created on 10/01/2012 of 99

VAL VS. VAR

object HelloScala {

def main(args: Array[String]) {

var msg = “Hello Scala”

println(msg)

msg = “Goodbye Java”

println(msg)

}

}

Page 21: All about scala

21 Created on 10/01/2012 of 99

METHODS (VERBOSE)

object HelloScala {

def main(args: Array[String]) {

println(hello(“Scala”))

}

def hello(who: String): String = {

return “Hello ” + who

}

}

Page 22: All about scala

22 Created on 10/01/2012 of 99

METHODS (SHORTER)

object HelloScala {

def main(args: Array[String]) {

println(hello(“Scala”))

}

def hello(who: String): String = {

“Hello ” + who

}

}

Page 23: All about scala

23 Created on 10/01/2012 of 99

METHODS (SHORTER YET)

object HelloScala {

def main(args: Array[String]) {

println(hello(“Scala”))

}

def hello(who: String) = {

“Hello ” + who

}

}

Page 24: All about scala

24 Created on 10/01/2012 of 99

METHODS (SHORT)

object HelloScala {

def main(args: Array[String]) {

println(hello(“Scala”))

}

def hello(who: String) = “Hello ” + who

}

Page 25: All about scala

25 Created on 10/01/2012 of 99

ARRAY ACCESS

object HelloScala {

def main(args: Array[String]) {

println(hello(args(0))

//args(0) is a shortcut for args.apply(0)

}

def hello(who: String) = “Hello ” + who

}

Page 26: All about scala

26 Created on 10/01/2012 of 99

CONDITION

object HelloScala {

def main(args: Array[String]) {

if (!args.isEmpty) println(hello(args(0))

}

def hello(who: String) = “Hello ” + who

}

//isEmpty() method has no arguments, and therefore can be invoked without the ()

Page 27: All about scala

27 Created on 10/01/2012 of 99

IF EXPRESSION, NOT STATEMENT

object HelloScala {

def main(args: Array[String]) {

println(hello(

if (args.isEmpty) “Anonymous” else args(0)))

}

def hello(who: String) = “Hello ” + who

}

Page 28: All about scala

28 Created on 10/01/2012 of 99

FUNCTION OBJECT

object HelloScala {

def main(args: Array[String]) { …

}

val hello = (who: String) => “Hello “ + who

// equivalent to

//val hello = new Function1[String, String] {

// def apply(who: String): String = “Hello “ + who

//}

}

Page 29: All about scala

29 Created on 10/01/2012 of 99

FOREACH

object HelloScala {

def main(args: Array[String]) {

args.foreach(arg => println(hello(arg)))

}

def hello…

}

//example of anonymous function object

Page 30: All about scala

30 Created on 10/01/2012 of 99

OPERATORS, INFIX SYNTAX

def hello(who: String) = “Hello ”.+(who)

//same as “Hello ” + who

//NOTE that this is an example, not a recommended coding style:

def main(args: Array[String]) {

Console println hello (if (args isEmpty) “Anonymous” else args apply 0)

}

Page 31: All about scala

31 Created on 10/01/2012 of 99

MATCH EXPRESSIONS

– Matching on values (Java’s switch)

val times = 1times match { case 1 => "one" case 2 => "two" case _ => "some other number" }

– No fall-through!

– Matching with guards

n match {  case it if 0 until 5 contains it  => "less than five"  case it if 5 until 10 contains it => "less than ten"  case _ => "a lot“}

Page 32: All about scala

32 Created on 10/01/2012 of 99

EXCEPTIONS

– Throwing an exception looks the same as in Java

– You catch exceptions using the syntax:

– NOTE: All exceptions in Scala are runtime

Page 33: All about scala

33 Created on 10/01/2012 of 99

CREATING A SEQUENCE

–Array(1,2,3)•Arrays are mutable

–List(3.14, 2.72, 1.62)•Lists are by default immutable, singly-linked•Nil is an empty list

–Map: val romanNumeral =

Map(1 ->"I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V“ )

// x -> y creates a tuple (x,y)

Page 34: All about scala

34 Created on 10/01/2012 of 99

MAP VALUES – ANOTHER OPTION

–What if key is not in the Map?

–Map.get returns an Option: •Some(value), value can be retrieved with get •or None

–getOrElse method allows to specify default:•treasureMap.getOrElse(1, “Oops”)•treasureMap.getOrElse(4, “Oops”)

–Safe alternative to null-checks

Scala Programming

Page 35: All about scala

35 Created on 10/01/2012 of 99

OPERATING WITH A SEQUENCE

– foreach(E=>Unit),

– filter(E=>Boolean),

– map(E=>X),

– reduceLeft((E,E)=>E),

– take(Int),

– drop(Int),

– indexOf(E),

– exists(E=>Boolean),

– remove(E=>Boolean),

– reverse,

– sort((E,E)=>Boolean),

– head,

– tail,

– … more later

Page 36: All about scala

36 Created on 10/01/2012 of 99

RICH WRAPPERS

– A Range can be created: ‘a’ to ‘z’ or 1 until 10

– Scala compiler made an implicit conversion of Int to scala.runtime.RichInt• To check if conversion is available: implicitly[Int => RichInt]

(in REPL first import scala.runtime._)• Alternatively: scalac –Xprint:typer

– Another Example: • reg-exp• "()?(\\d+)(\\.\\d*)?".r

Page 37: All about scala

37 Created on 10/01/2012 of 99

PLACEHOLDER

(1 to 10) filter ((i: Int) => i%2 == 0) mkString “,”

or equivalent shorter version:

… filter (i => i%2 == 0)

or yet shorter using placeholder:

… filter (_ %2 == 0)

(1 to 10).reduceLeft((acc: Int, i: Int) => acc + i)

or equivalent shorter version:

… reduceLeft((acc, i) => acc + i)

or yet shorter using placeholders:

… reduceLeft(_ + _)

Page 38: All about scala

38 Created on 10/01/2012 of 99

CLOSURES

–So far, function literals have referred only to passed parameters(x: Int) => x > 0

–You can, however, refer to variables defined elsewhere(x: Int) => x + more // how much more?

–more is a free variable, because the function literal does not itself give a meaning to it.

–x variable, by contrast, is a bound variable.

Page 39: All about scala

39 Created on 10/01/2012 of 99

CLOSURES

The function value (the object) that’s created at runtime from addMore function literal is called a closure.

The name arises from the act of “closing” the function literal by “capturing” the bindings of its free variables

Page 40: All about scala

40 Created on 10/01/2012 of 99

EXAMPLEdef tryWithLogging (s: => Unit) {

try {

s

} catch {

case ex: Exception => ex.printStackTrace()

}

}

val file = new File(“test.txt”)

tryWithLogging {

val writer = new PrintWriter(file)

writer.println(“this is a test”)

}

If you’re passing exactly one argument to a method, you can use curly braces instead of parentheses to surround it.

Page 41: All about scala

41 Created on 10/01/2012 of 99

HELLO SCALA – FOR COMPREHENSION

object HelloScala {

def main(args: Array[String]) {

for (arg ← args) println(hello(arg)))

}

def hello…

}

Page 42: All about scala

42 Created on 10/01/2012 of 99

MORE ON FOR EXPRESSION

–map alternative – yield:def scalaFiles =

for {

file (new java.io.File(".")).listFiles

if file.getName.endsWith(".scala")

} yield file

•When the for expression completes, the result will include all of the yielded values contained in a single collection.

•The type of the resulting collection is based on the kind of collections processed in the iteration clauses.

Page 43: All about scala

43 Created on 10/01/2012 of 99

SCALA HIERARCHY

– Nothing is the subtype of all other types. • It has no instances. • It is used primarily for defining other types in a

type-safe way, such as the special List subtype Nil.

– Null has one instance, null, corresponding to the runtime’s concept of null.

– FunctionN[-T1, -T2, …, -TN, +R] a

function that takes N arguments

– Product - arity and getting nth item in a “cartesian product”. • Subtraits are defined for Product,

called ProductN, for dimension N from 1 through 22.

– TupleN case classes for arity N = 1 through 22. • Tuples support the literal syntax (x1, x2, …, xN)

Page 44: All about scala

44 Created on 10/01/2012 of 99

CLASSES

OOP in Scala

Page 45: All about scala

45 Created on 10/01/2012 of 99

SIMPLE CLASS

–Like in Java classes are defined with class and instances created with new

–Declaring properties is much simpler

Java

public class Person { private String name = null; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; }}

Scala

class Person (var name: String)

…person = new Person(“Martin”)println(person.name)

Page 46: All about scala

46 Created on 10/01/2012 of 99

SIMPLE CLASS

scala> class Lang {

| val name: String = “Scala"

| def add(m: Int, n: Int): Int = m + n

| }

defined class Lang

scala> val lang = new Lang

lang: Lang = Lang@e74a51

scala> lang.add(1, 2)

res1: Int = 3

scala> lang.name

res2: String = “Scala"

Page 47: All about scala

47 Created on 10/01/2012 of 99

CLASS SYNTAX

Page 48: All about scala

48 Created on 10/01/2012 of 99

EXTENDING CLASSES

class ArrayElement(conts: Array[String]) extends Element {

def contents: Array[String] = conts

}

class LineElement(s: String) extends ArrayElement(Array(s)) {

override def width = s.length

override def height = 1

}

Page 49: All about scala

49 Created on 10/01/2012 of 99

SINGLETON & COMPANION OBJECTS

– Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, Scala has singleton objects.

– A singleton object definition looks like a class definition, except instead of the keyword class you use the keyword object.

– When a singleton object shares the same name with a class, it is called that class’s companion object. object Rational {

}

– A singleton object that does not share the same name with a companion class is called a standalone object.

Page 50: All about scala

50 Created on 10/01/2012 of 99

COMPANION OBJECT AS A FACTORY

– Companion objects are excellent fit for implementing Factory design patterns

– Naming the method apply allows invocation like Array(“a”, “b”, “c”) instead of Array.apply(“a”, “b”, “c”)

Page 51: All about scala

51 Created on 10/01/2012 of 99

BUILDER PATTERN IN SCALA

– From Josh Bloch’s “Effective Java” 2nd ed.: public class NutritionFacts { private final int servingSize; // (mL) required private final int servings; // (per container) required private final int calories; // optional private final int fat; // (g) optional private final int sodium; // (mg) optional private final int carbohydrate;// (g) optional … }

– In Scala:class NutritionFacts(servingSize, servings, calories = 0, fat = 0, sodium = 0, carbohydrate = 0)

Creating an instance:

new NutritionFacts(servings = 3, servingSize = 200, fat = 1)

Page 52: All about scala

52 Created on 10/01/2012 of 99

CASE CLASSES – VALUE OBJECTScase class Point(x: Double, y: Double)

abstract class Shape() { def draw(): Unit }

case class Circle(center: Point, radius: Double) extends Shape() {

def draw() { … }

}

case class Rectangle(x: Point, height: Double, width: Double) extends Shape() {

def draw() { … }

}

case class Triangle(point1: Point, point2: Point, point3: Point) extends Shape() {

def draw() { … }

}

– Using the case modifier makes the Scala compiler add some syntactic conveniences to your class•…

Page 53: All about scala

53 Created on 10/01/2012 of 99

CASE CLASS MAGIC

– Compiler automatically creates factory method: val c = Circle(Point(2.0,1.0),3.0) instead of

val c = new Circle(new Point(2.0,1.0),3.0)

– All constructor arguments automatically become immutable fields

– Compiler automatically implements equals, hashCode, and toString methods to the class, using the fields specified as constructor argumentscase classes are always compared structurally

– Compiler adds a copy method for making modified copiesThe method works by using named and default parameters. You specify the changes you’d like to make by using named parameters. For any parameter you don’t specify, the value from the old object is used.

val r = Rectangle(Point(1.0,2.0), 3.0, 4.0)

r.copy(height=5.0)

– We can pattern match on case classes…

Page 54: All about scala

54 Created on 10/01/2012 of 99

CASE CLASSES – PATTERN MATCHING

def matchOn(shape: Shape) = shape match {

case Circle(center, radius) => println("Circle: center = "+center+", radius = "+radius)

case Rectangle(x, h, w) => println("Rectangle: lower-left = "+x+", height = "+h+", width = "+w)

case Triangle(p1, p2, p3) => println("Triangle: point1 = "+p1+", point2 = "+p2+", point3 = "+p3)

case _ => println("Unknown shape!"+shape)

}

val shapesList = List(

Circle(Point(0.0, 0.0), 1.0), Circle(Point(5.0, 2.0), 3.0), Rectangle(Point(0.0, 0.0), 2, 5), Rectangle(Point(-2.0, -1.0), 4, 3), Triangle(Point(0.0, 0.0), Point(1.0, 0.0), Point(0.0, 1.0))

)

shapesList.foreach { shape => matchOn(shape) }

Page 55: All about scala

55 Created on 10/01/2012 of 99

MIXIN COMPOSITION WITH TRAITS

Page 56: All about scala

56 Created on 10/01/2012 of 99

TRAITS

– A trait definition looks just like a class definition except that it uses the keyword traittrait Philosophical { def philosophize() { println("I consume memory, therefore I am!") }}

– Once a trait is defined, it can be mixed in to a class using either the extends or with keywordsclass Frog extends Philosophical { … }

– Traits facilitate multiple inheritance: a class can mix in any number of traits. “He who defs last defs best”.class Animal { … } trait HasLegs { val legsNumber : Int }class Frog extends Animal with Philosophical with HasLegs { override val legsNumber = 4override def philosophize() { println(“It ain't easy being green”) }}

Page 57: All about scala

57 Created on 10/01/2012 of 99

THE TRAITS OF TRAITS

– Traits can be also mixed in when creating individual objects:val frog = new Animal with Philosophical

– You can do anything in a trait definition that you can do in a class definition, with only two exceptions:• trait cannot have any “class” parameters, i.e., parameters passed to the primary constructor of a classtrait NoPoint(x: Int, y: Int) // Does not compile

• in classes, super calls are statically bound, in traits, they are dynamically bound (enables stackable modifications pattern)

– Trait, like any class can have a companion object• selfless trait – trait Util { … }; object Util extends Util

Page 58: All about scala

58 Created on 10/01/2012 of 99

TRAITS – A PRACTICAL EXAMPLE

class Trade(refNo: String, account: String, instrument: String,                   quantity: Int, unitPrice: Int) {  // principal value of the trade  def principal = quantity * unitPrice}

trait Tax {   def calculateTax }

trait Commission {   def calculateCommission}

val trade = new Trade(..) with Tax with Commission {  // implementations  def calculateTax = principal * 0.2  def calculateCommission = principal * 0.15}

Page 59: All about scala

59 Created on 10/01/2012 of 99

TRAITS – REQUIRE (SELF TYPE)

– Sometimes you want to constrain what the trait can be mixed in with, for example:// abstractions Tax and Commission should be constrained to be used with the Trade abstraction only

trait Tax { self: Trade =>  def calculateTax = principal*0.2 //refers to principal of trade }

trait Commission { self: Trade =>  def calculateCommission = principal*0.15  //refers to principal of trade}

– When you say B extends A, then B is an A, while here you define the relationship of B requires an A

Page 60: All about scala

60 Created on 10/01/2012 of 99

TRAITS – DI WITH THE CAKE PATTERN

– The pattern based on Scala traits was first introduced by Martin Odersky’s paper “Scalable Component Abstractions”

– The pattern also uses nested classes: Scala, like Java, supports nesting of classes in one another

– Demo

http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html

Page 61: All about scala

61 Created on 10/01/2012 of 99

ANNOTATIONS – JPA EXAMPLE@Entity @NamedQuery{val name = "findAllBook", val query = "SELECT b FROM Book b"}

class Book extends Id with Description { @Column{val nullable = false} @BeanProperty var title: String @BeanProperty var price: Float   @BeanProperty var isbn: String   @BeanProperty var nbOfPage: Int @BeanProperty var illustrations: Boolean }trait Id { @javax.persistence.Id @GeneratedValue{val strategy = GenerationType.IDENTITY} @BeanProperty var id: Long}trait Description { @Column{val length = 2000} @BeanProperty var description: String }

Page 62: All about scala

62 Created on 10/01/2012 of 99

PACKAGES

– You can place code into named packages in Scala:• Either place the contents of an entire file into a package by putting a package clause at the top of the file (like in Java)

• Or follow a package clause by a section in curly braces that contains the definitions that go into the package (like C# namespaces).

–  Objects are a useful tool for organizing static functions.

Page 63: All about scala

63 Created on 10/01/2012 of 99

PACKAGE OBJECTS

– Scala version 2.8 introduces a new scoping construct called package objects• they are used to define types, variables, and methods that are visible at the level of the corresponding package

• they can contain aliases to classes and objects• they provide a clear separation between the abstractions exposed by a package and the implementations that should be hidden inside it

package object scala { type Iterable[+A] = scala.collection.Iterable[A] val Iterable = scala.collection.Iterable…

}

Page 64: All about scala

64 Created on 10/01/2012 of 99

IMPORT

– Use import in REPL and anywhere in your .scala file • Single file: import package.Class • All files: import package._• Multiple files: import package.{A,B,C}• Renaming: import package.{A=>B}• Import all except: import package.{A=>_, _}

– Example: import java.sql.{Date=>SDate,_}

– Imports are relative, but you can use _root_. … to import a FQN

– Import also works with Objects

– You can limit the scope of any declaration, including import, with locally { … }

Page 65: All about scala

65 Created on 10/01/2012 of 99

FUNCTIONAL PROGRAMMINGBASICS

Unleash the power of Lambda

Page 66: All about scala

66 Created on 10/01/2012 of 99

OVERVIEW

– In mathematics, functions have no side effects• No matter how much work sin(x) does, all the results are returned and assigned to y. No global state of any kind is modified internally by sin(x). Hence, we say that such a function is free of side-effects or pure.

– This obliviousness to the surrounding context is known as referential transparency. • You can call such a function anywhere and be confident that it will always behave the same way. If no global state is modified, concurrent invocation of the function is straightforward and reliable.

Page 67: All about scala

67 Created on 10/01/2012 of 99

OVERVIEW

– In functional programming variables are immutable.• In the expression y = sin(x), once you pick x, then y is fixed

• Functional programming languages prevent you from assigning a new value to a variable that already has a value.

• Besides concurrency, immutability has other benefits…

– “Functional manifesto”• val over var

• Composition over inheritance

• Immutable collections

• Recursion over imperative iteration

• Pattern matching over encapsulation

• …

Page 68: All about scala

68 Created on 10/01/2012 of 99

LAZY VAL

– If you prefix a val definition with a lazy modifier, the initializing expression on the right-hand side will only be evaluated the first time the val is used.

– unlike def, lazy val is never evaluated more than once.• after the first evaluation of a lazy val the result of the evaluation is stored, to be reused when the same val is used subsequently.

Page 69: All about scala

69 Created on 10/01/2012 of 99

CALL BY NAME PARAMETERS

–Typically, parameters to functions are by-value parameters – the value of the parameter is determined before it is passed to the function

–Sometimes we don’t want a parameter evaluated until it’s accessed within our function

–A by-name parameter is specified by omitting the parentheses that normally accompany a function parameterdef myCall (parameter: => ReturnType)

Page 70: All about scala

70 Created on 10/01/2012 of 99

CALL BY NAME PARAMETERS USE-CASE– When logging, we create messages by concatenating Strings, even

if we don't use these messages in the end because the logging level is not enabled.

– To fix the problem, we often insert manual checks in client code whether the logging level is enabled, e.g. by calling if (logger.isDebugEnabled()) logger.debug(…)

– SLF4S, Scala logging library, uses by-name parametersdef debug(msg: => String) { require(msg != null, "msg must not be null!") if (slf4jLogger.isDebugEnabled) slf4jLogger debug msg}

– SLF4S also provides Logging trait that can be mixed in into any classclass MyClazz extends SomeClazz with Logging...logger debug "SLF4S just rocks!"...

Page 71: All about scala

71 Created on 10/01/2012 of 99

CURRYING

– Currying – a way to write functions with multiple parameter lists. • For instance def f(x: Int)(y: Int) is a curried function with two parameter lists.

• A curried function is applied by passing several arguments lists, as in: f(3)(4).

– Examples:def plainOldSum(x: Int, y: Int) = x + yplainOldSum(1, 2)

def curriedSum(x: Int)(y: Int) = x + ycurriedSum(1)(2)

val onePlus: (Int) => Int = curriedSum(1)_

onePlus(2) //3

Page 72: All about scala

72 Created on 10/01/2012 of 99

CURRYING EXAMPLE

– foldLeft/Right

– withResource (the loan pattern)def using[R <: Closeable] (resource: R)(block: R => Unit) {  try {    block(resource)  } finally {    if (resource != null) resource.close()  }}

• Usage Example:

using(new BufferedReader(new FileReader("file"))) { r =>  … r.readLine …}

Page 73: All about scala

73 Created on 10/01/2012 of 99

PARTIALLY-APPLIED FUNCTIONS

– A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.scala> def sum(a: Int, b: Int, c: Int) = a + b + c

sum: (a: Int,b: Int,c: Int)Int

scala> val a = sum _

a: (Int, Int, Int) => Int = <function3>

a(1, 2, 3) //6

supplying some arguments: val b = sum(1, _: Int, 3)

b: (Int) => Int = <function1>

scala> b(2) //6

Page 74: All about scala

74 Created on 10/01/2012 of 99

CONCURRENCY IN SCALA

Introducing Actors

Page 75: All about scala

75 Created on 10/01/2012 of 99

MOTIVATION

Moor’s Law• “The number of transistors on a chip will double approximately every 18 months”

Gordon E. Moore, 1965

Free LunchFree and regular performance gains, even without releasing new versions or doing anything special

Page 76: All about scala

76 Created on 10/01/2012 of 99

FREE LUNCH IS OVER

– Hardware crossed a boundary in the early 2000s: • chips got big enough, cycle speed got fast enough • a signal can no longer reach the whole chip in a clock cycle• problems with heat dissipation

– Processor manufacturers have turned towards multi-core processors Capable of doing multiple calculations in parallel • CPU speeds are likely to stay relatively flat in the near future • The speedup of a program using multiple processors in parallel computing is limited by the sequential fraction of the program.

Page 77: All about scala

77 Created on 10/01/2012 of 99

SHARED STATE CONCURRENCY

–Shared mutable state is problematic

–We need locking mechanism

–Thread concurrently executes code sections•Contains resources that must be shared•Synchronized in order to guarantee

−Correct ordering

−Visibility

−Data consistency

Page 78: All about scala

78 Created on 10/01/2012 of 99

PROBLEMS WITH LOCKING

–Hard to program correctly•Race conditions•Also hard to test and debug

–Synchronizing too much•Deadlocks•Makes your program serial

Page 79: All about scala

79 Created on 10/01/2012 of 99

ALTERNATIVES

–Message Passing Concurrency (Actors)

–Software Transactional Memory

–Dataflow Concurrency

Page 80: All about scala

80 Created on 10/01/2012 of 99

ACTORS

–Message-passing instead of shared state

–Originated: •Carl Hewitt (early 70s)•Gul Agha (80s)

–Popularized by Erlang implementation•A pure functional, dynamically typed language invented in 1986 at Ericsson

–Actors are related to original OO ideas •Actors encapsulate state and behavior (like objects)•Actors are logically active (unlike most objects)

Page 81: All about scala

81 Created on 10/01/2012 of 99

ACTORS

– No shared state between actors

– Asynchronous message-passing

– Mailbox to buffer incoming messages

– React to received messages by executing a behavior function•can only change the state of the actor itself

•can send messages to other actors

– Actors never share state and thus never need to compete for locks for access to shared data

Page 82: All about scala

82 Created on 10/01/2012 of 99

AKKA

– Akka is the platform for next generation event-driven, scalable, and fault-tolerant architectures on the JVM

– Written in Scala, can be used with Scala or Java

– Each actor instance runs in only one thread at a time, so no synchronization is required for actor state.

– Akka dispatcher schedules actors on threads – or even on multiple machines – as needed. Can have millions of actors, an actor does not “use up” a thread.

Page 83: All about scala

83 Created on 10/01/2012 of 99

SIMPLE AKKA ACTOR

case object Tick

class Counter extends Actor {

private var counter = 0

def receive = {

case Tick =>

counter += 1

println(counter)

}

}

val counter = actorOf[Counter]

counter.start

Page 84: All about scala

84 Created on 10/01/2012 of 99

SEND

–Fire and forgetcounter ! Tick

–Uses Future under the hood (with time-out)val result = (actor !! Message).as[String]

–Returns the Future directlyval future = actor !!! Message

future.await

val result = future.get

...

Futures.awaitOne(List(fut1, fut2, ...))

Futures.awaitAll(List(fut1, fut2, ...))

Page 85: All about scala

85 Created on 10/01/2012 of 99

REPLY

class SomeActor extends Actor {

def receive = {

case User(name) =>

// use reply

self.reply(“Hi ” + name)

}

}

store away the sender to use later or somewhere else

... = self.sender

Page 86: All about scala

86 Created on 10/01/2012 of 99

SCALA AND AKKA

– Immutable messages : case classes, tuples, lists

– Dispatchers

– Let it fail – Supervisor Hierarchies• One for One

• All for One

• Supervise the supervisor

– Remote actors

– Transactors: STM using Actors

Page 87: All about scala

87 Created on 10/01/2012 of 99

TOOLS

Build, testing, etc.

Page 88: All about scala

88 Created on 10/01/2012 of 99

SBT – SIMPLE BUILD TOOL

– Build your projects using Scala

– Create an sbt shell script: java -Xmx512M -jar sbt-launch.jar "$@“

– Launch it: sbt

– Interactive mode: e.g. compile

– Make an action run when a source file changes prefixing the action with ~.

– project/build/SbtDemoProject.scalaimport sbt._

class SbtDemoProject(info: ProjectInfo) extends DefaultProject(info) {

val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5" % "test"

lazy val hi = task { println("Hello World"); None }

override def compileOptions = super.compileOptions ++ Seq(Unchecked)

}

– In sbt console: reload

– In sbt console: hi

<dependency> <groupId>org.scala-tools.testing</groupId> <artifactId>specs_2.8.0</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency>

Page 89: All about scala

89 Created on 10/01/2012 of 99

PLAY! FRAMEWORK

– Both Scala and Java friendly

– Stateless• Play is “share-nothing” so no need for communication between nodes

• State can be kept in your SQL or NoSQL store, in memcached, or browser cookies

– Emphasis on rapid development and good defaults, rather than absolute flexibility• No compile and restart; server compiles and recompiles on the fly, so just edit, reload, edit, reload. Compilation and other errors appear right in the browser.

– Try out the Java or Scala tutorials on the Play website

play new helloworld --with scala

play run

Page 90: All about scala

90 Created on 10/01/2012 of 99

UNIT TESTING

–To test in Scala you can use Java tools:• JUnit•TestNG

–Or frameworks built especially for Scala:•ScalaTest•Specs•ScalaCheck

Scala Programming

90

Page 91: All about scala

91 Created on 10/01/2012 of 99

UNIT TESTING

Page 92: All about scala

92 Created on 10/01/2012 of 99

UNIT TESTING – SCALATEST + JUNIT

– If you wish to use ScalaTest’s assertion syntax in your JUnit 3 test, however, you can instead subclass JUnit3Suite

– ScalaTest also has a JUnitWrapperSuite, which enables you to run existing JUnit tests written in Java with ScalaTest’s runner.

Page 93: All about scala

93 Created on 10/01/2012 of 99

TEST AS SPECIFICATION

Page 94: All about scala

94 Created on 10/01/2012 of 99

TEST AS SPECIFICATION

– In a FlatSpec, you write tests as specifier clauses. • You start by writing a name for the subject under test as a string,

• then should (or must or can),

• then a string that specifies a bit of behavior required of the subject,

• then in.

• In the curly braces following in, you write code that tests the specified behavior.

• In subsequent clauses you can write it to refer to the most recently given subject.

– When a FlatSpec is executed, it will run each specifier clause as a ScalaTest test. • FlatSpec (and ScalaTest’s other specification traits) generate output that reads more

like a specification when run.

Scala Programming

94

Page 95: All about scala

95 Created on 10/01/2012 of 99

TEST AS SPECIFICATION - SPECS

– specs is another open source testing framework inspired by Ruby’s RSpec

Page 96: All about scala

96 Created on 10/01/2012 of 99

PROPERTY-BASED TESTING

– ScalaCheck enables you to specify properties that the code under test must obey.

– For each property, ScalaCheck will generate test data and run tests that check whether the property holds.

Page 97: All about scala

97 Created on 10/01/2012 of 99

RESOURCES

Read more about Scala

Page 98: All about scala

98 Created on 10/01/2012 of 99

MORE ON SCALA

– http://www.scala-lang.org

– http://typesafe.com/

– Scala School http://twitter.github.com/scala_school/

– Programming In Scala http://www.artima.com/pins1ed/

– Programming Scala http://ofps.oreilly.com/titles/9780596155957/

– Scala Style Guide http://davetron5000.github.com/scala-style/

– StackOverflow http://stackoverflow.com/questions/tagged/scala

Page 99: All about scala

99 Created on 10/01/2012 of 99

THANK YOUIf you are interested in programming languages,

join http://www.lambda.org.il