SlideShare une entreprise Scribd logo
1  sur  60
Introduction toCoding in Scala is fun! OOP 2010 Dr. Michael Stal Michael.Stal@siemens.com
Objectives of this Presentation Introduce core concepts of Scala Showing you the benefits of combining OO with functional programming Illustrating the language in a pragmatic way preferring code over theory But not to cover every available aspect or to cover aspects in full  detail For instance, we won‘t cover Java/Scala Interop, Views, Equality Semantics, Unit Testing, Annotations Page 2
Introduction Scala created by the team of Martin Odersky at EPFL „Scala“ means „Scalable Language“ „Scalable“ means:  the same language concepts for programming in the small & large In Scala this is achieved in a pragmatic way by combining  Object Oriented Programming with Functional Programming  Scala is a statically typed language like Java All types are objects Page 3 Martin Odersky, Source: http://lamp.epfl.ch/~odersky/
Object-Oriented & Functional Programming Object-Oriented Programming Abstraction using Classes and Interfaces Refinement using subtyping and inheritance (Remember the Liskov Substitution Principle!) Dynamics through polymorphism Functional Programming Higher Order Functions as First-Class Entities ADTs (Abstract Data Types) following algebraic conventions Pattern matching Parametric polymorphism (generic types) Page 4 SCALA
Core Properties of Scala (see Programming in Scala) Scala is compatible: runs on JVM, interoperability with Java Scala is concise: More compact code because removal of Java boilerplate code and powerful libraries Scala is high-level: Higher level of abstraction by combining OO with functional programming Scala is statically typed Page 5 Scala‘s Roots: ,[object Object]
 Smalltalk, Ruby
 Beta, Simula, Algol
 ML
 Erlang,[object Object]
Stairway to Heaven – First Steps using Scala  This source code file may be compiled using scalac und run using scala: scalac HelloWorldMain.scala scala HelloWorldMain  Note: the source file must be named like the main object to be executed  You may run an interpreter by using the following command line instead scala HelloWorldMain.scala  In this case you may also use plain Scala scripts (no classes or objects required) Or, even better, you might use an IDE like Idea, Netbeans, or Eclipse Page 7
A more advanced example (1)  (from Venkat Subramanian‘s book Programming Scala, pp.5) Page 8 import scala.actors._ import Actor._ val symbols = List( "AAPL", "GOOG", "IBM", "JAVA", "MSFT") val receiver = self val year = 2009 symbols.foreach {    symbol =>  actor { receiver ! getYearEndClosing(symbol, year) } } val (topStock, highestPrice) = getTopStock(symbols.length) printf("Top stock of %d is %s closing at price %f", year, topStock, highestPrice) def getYearEndClosing(symbol : String, year : Int) = {     val url = new        java.net.URL("http://ichart.finance.yahoo.com/table.csv?s=" +     symbol + "&a=11&b=01&c=" + year + "&d=11&e=31&f=" + year + "&g=m")         val data = io.Source.fromURL(url).mkString     val price = data.split("")(1).split(",")(4).toDouble       (symbol, price) } // .. to be continued
A more advanced example (2)(from Venkat Subramanian‘s book Programming Scala, pp.5) Run this within interpreter mode scala TopScala.scala After the end of the talk return to this example and check whether you better understand it Page 9 // continued ... def getTopStock(count : Int) : (String, Double) = {      (1 to count).foldLeft("", 0.0) { (previousHigh, index) =>          receiveWithin(10000) {              case (symbol : String, price : Double) =>                    if (price > previousHigh._2) (symbol, price)             else previousHigh          }      } }  // will result in => // Top stock of 2009 is GOOG closing at price 619,980000
Scala Type Hierarchy Page 10 Scala uses a pure object-oriented type system Every value is an object Two types: values and references Any is parent class of all classes, Nothing subclass of all classes Basic types like in Java Source: Scala Reference Manual
First Class Scala Page 11 born and  id will be public fields Main constructor Classes in Scala contain fields, methods, types, constructors Visibility is public per default class CatID(val id : Int)  //that's a whole class class Cat(val born: Int, val id: CatID) { private var miceEaten: Int = 0    def digested() = miceEaten def hunt(miceCaught: Int)               { miceEaten +=  miceCaught } } object ScalaClasses {    def main(args: Array[String]) {      val id = new CatID(42)      val tom = new Cat(2010, id)      tom.hunt(3)      tom hunt 2      println(“cat was born in “ + tom.born)       println(tom.digested)    } } // => 5 <> Tom was born in 2010  definition of methods No brackets required
Class Constructors Page 12 class Complex (r : Double, i: Double) {   println("Constructing a complex number")   val re = r   val im = i   def this(r : Double) = this(r,0)   override def toString =          re + (if (im < 0) "-" + (-im)               else "+" + im) + "*i"   ... } Belongs to Primary constructor Auxilliary constructorsmust call primary
Immutable and Mutable Objects Scala provides immutable objects (functional programming) but also mutable objects Immutability has many benefits Reduction of race conditions in concurrent programs Protection against unwanted modification Scala provides mutable & immutable versions of collection types Mutable objects are important to address objects that are supposed to change their state, but use them with care Page 13 class Person(var name: String) object ImmutabilityDemo {  def main(args:Array[String]) = { val s = "Michael"    s = "Bill" // error var t = "Michael“ // t variable    t = "Bill" // ok    val c = new Person("Bill")    c = new Person("Tom") // error // ok - c itself unchanged:    c.name = "Tom"  } }
Inheritance In Scala classes can be derived from at most one base class Classes may be abstract You need to indicate whether you override inherited methods Page 14 abstractclass Shape { type Identifier = Int // defining types   def getID() : Identifier = 42   def draw() : String   // abstract method } class Circle (val cx: Double, val cy: Double, val r: Double) extends Shape {   val id : Identifier = getID() override def draw() : String = "I am a Circle" }
Companion Objects and Standalone Objects We already saw standalone objects Objects are singletons If you need static fields or methods for a class, introduce a companion class with the same name Convention: apply() methods may be provided as factory methods Page 15 class Cat private (val born : Int, val id: CatID) {    ... private def this(id: CatID) = this(2010, id)    ... } // all constructors are private object Cat { // this is the companion object of Cat def apply(born: Int, id: CatID) =  new Cat(born, id)    def apply(id: CatID) = new Cat(id) // factory method    def whatCatsDo() = "Sleep, eat, play"	 } object ScalaClasses { // Standalone Object    def main(args: Array[String]) {      val id = new CatID(43) val pussy = Cat(id) // no new required      println("Pussy was born in " + pussy.born)      println(Cat.whatCatsDo)  // like static in Java      } }
Application Base Class For experimenting with Scala use the base class Application Just compile this with: scalac ObjDemo.scala And run it with: scala ObjDemo Useful abbreviation if you do not need to deal with command line arguments Page 16   Inheritance object ObjDemoextends Application { val s: String = "Michael" println(s) // => Michael }
Traits Classes and instances may mix-in additional functionality using traits Traits represent an abstraction between interfaces and classes Using traits we can easily live with the single-inheritance restriction You may use also traits via anonymous classes: 	val x = new Identity{}   	x.name = "UFO"   	println(x.whoAmI) Page 17 trait   Identity  {    var name: String=""    def whoAmI() : String = name	 } class  Person extends Identity  class Animal object TraitDemo {  def main(args:Array[String]) = {    val p = new Person    p.name = "Michael"    println(p.whoAmI) val a = new Animal with Identity    a.name = "Kittie"    println(a.whoAmI)  } } // => Michael <> Kittie
Traits and Virtual Super: Inheritance Linearization Page 18 abstract class Processor { def process() } trait Compressor extends Processor { // trait only applicable to Processor subclass abstract override def process() =  { println("I am compressing"); super.process } } trait Encryptor extends Processor { // only applicable to Processor subclass abstract override def process() = { println("I am encrypting"); super.process} } class SampleProcessor extends Processor { // subclass of Processor     override def process() = println("I am a Sample Processor") } object traitsample2 {     def main(args:Array[String]) = { // mixing in a trait to an object: val proc1 = new SampleProcessor with Compressor with Encryptor proc1.process// Encryptor.process=>Compressor.process      }                        //                                   => SampleProcessor.process } Note: abstract override for a trait method means the actual subclass of Processor will provide a concrete implementation of that method!
Scala Basics: if Statements If statements are expressions themselves, i.e. they have values Page 19 import java.util._ if (1 + 1 == 3)  println(“strange world”)  else { println(“everything’s ok”) } val res = if ((new Random().nextInt(6) + 1) == 6)  		"You win!"  	    else              "You lose!"
Scala Basics: for Comprehensions (1) A for comprehension is like a for loop. It lets you traverse a collection, return every object in a temporary variable which is then passed to an expression. You may also specify nested iterations: You can specify filters for the collection elements Page 20 val aList  = List(1,2,3,4,5,6) for (i <- aList) println(i) // => 1 <> 2 ... val dogs = Set("Lassie", "Lucy", "Rex", "Prince"); for (a <- dogs if a.contains("L")) println(a) // => “Lassie” <> “Lucy”
Scala Basics: for Comprehensions (2) Yield allows to create new collections in a for comprehension: You can specify filters for the collection elements Page 21 var newSet = for {                    a <- dogs                    if a.startsWith("L")              } yield a println(newSet)  // Set(Lassie, Lucy) for {      i <- List(1,2,3,4,5,6)     j = i * 2 // new variable j defined } println(j) // => 2 <> 4 <> 6 ...
Scala Basics: Other loops Scala supports while and do-while loops But generator expressions such as (1 to 6)  incl. 6 or (1 until 6) excl. 6 together with for make this much easier Note: The reason this works is a conversion to RichInt where to is defined as a method that returns an object of type Range.Inclusive, an inner class of Range implementing for comprehensions Page 22 var i = 1 while (i <= 6)  {     println(i)     i  += 1 } // = 1 <> 2 <> 3 ...  for (i <- 1 to 6) println(i)
Scala Basics: Exception handling try-catch-finally available in Scala but throws isn‘t catching checked exceptions is optional! catch-order important as in Java, C++ or C# Page 23 def temperature(f: Double) {   if (f < 0) throw new IllegalArgumentException() } try {    println("acquiring resources")    temperature(-5) } catch {    case ex:  IllegalArgumentException => println("temperatur < 0!")    case _ => println("unexpected problem") } finally {    println("releasing resources") }
Inner Classes You may define inner classes as in Java Special notation (<name> =>)  for referring to outer class this from an inner class: you might also use <outerclass>.this instead Page 24 class Element (val id: String){ elem => class Properties { // inner class type KV = Tuple2[String, Any]     var props: List[KV] = Nil     def add(entry: KV) { props = entry :: props }     override def toString = {       var s: String = ""       for (p <- properties.props) s = s + p +""       s     } }   override def toString = "ID = " + id + "" + properties   val properties = new Properties   } object InnerClassDemo extends Application {   val e = new Element("Window")   e.properties.add("Color", "Red")   e.properties.add("Version", 42)   println(e.toString) }
Imports and Packages We can partition Scala definitions into packages: A package is a special object which defines a set of member classes, objects and packages. Unlike other objects, packages are not introduced by a definition Importing packages works via import statements – almost like in Java Packages scala, java.lang, scala.Predefare automatically imported Page 25 package MyPackage1 {    class Person(val name: String)    class Animal(val name: String) } import MyPackage1._ object PacDemo extends Application {    val person = new Person("Michael")    println(person name) } ,[object Object],                                  to import p.* in Java).  ,[object Object]
 import p.{x => a}   the member x of p renamed as a.
 import p.{x, y}       the members x and y of p.
 import p1.p2.z       the member z of p2, itself member of p1.,[object Object]
Advanced Types: Sets Collection Type: Set Page 27 object SetDemo {  def main(args:Array[String]) { val s1 = Set[Int](1,2,3,4,5) // we could also use = Set(1,2,3,4,5) val s2 = Set[Int](2,3,5,7) println(s2.contains(3))  // => true val s3 = s1 ++ s2 // union println(s3) // => Set(5,7,3,1,4,2) vals4 = s1 & s2 // intersection: in earlier versions ** println(s4) // Set(5,3,2)   } }
Advanced Types: Maps Collection Type: Map Page 28 object MapDemo {  def main(args:Array[String]) { val m1 = Map[Int, String](1 -> "Scala", 2->"Java", 3->"Clojure") valm2 = m1 + (4 -> "C#") // add entry println(m2 + " has size " + m2.size)                             //=> Map(1->Scala,…) has size 4 println(m1(1)) // => Scala val m3 = m2 filter { element => val (key, value) = element                     (value contains "a") }   println(m3) // => Map(1->Scala, w->Java)  } }
Advanced Types: Options object DayOfWeek extends Enumeration {   val Monday    = Value("Monday") //argument optional    val Sunday    = Value("Sunday") //argument optional  } import DayOfWeek._  object OptionDemo {  def whatIDo(day: DayOfWeek.Value) : Option[String] =      {     day match {       case Monday  => Some("Working hard")       case Sunday  => None     }  }  def main(args:Array[String]) {    println(whatIDo(DayOfWeek.Monday))     println(whatIDo(DayOfWeek.Sunday))   } //=> Some(„Working Hard“) <> None } The Option type helps dealing with optional values For instance, a search operation might return  a result or nothing We are also introducing Enumerationtypes Page 29
Advanced Types: Regular Expressions Type: Regex introduces well-known regular expressions Page 30 With this syntax strings remain formatted as specified and escape sequences are not required object RegDemo {  def main(args:Array[String]) { val pattern = """""".r val sentence = “X was born on 01.01.2000 ?" println (pattern findFirstIn sentence) // => Some(01.01.2000)  } } Note: the „r“ in “““<string>“““.r means: regular expression
Advanced Types: Tuples Tuples combine fixed number of Elements of various types Thus, you are freed from creating heavy-weight classes for  simple aggregates Page 31 println( (1, "Douglas Adams", true) ) def goodBook = { ("Douglas Adams", 42, "Hitchhiker's Guide") }         println ( goodBook._3 ) // get third element // => (1, Douglas Adams, true) // => Hitchhiker‘s Guide
Advanced Types: Arrays Arrays hold sequences of elements Access very efficient Page 32 val a1 = new Array[Int](5) // initialized with zeros  val a2 = Array(1,2,3,4,5) // initialized with 1,2,3,4,5 println( a2(1) ) // => 2 a2(1) = 1 // => Array (1,1,3,4,5) Note: In Scala the assignment operator = does not return a reference to the left variable (e.g., in a = b). Thus, the following is allowed in Java but not in Scala: a = b = c
Smooth Operator In Scala operator symbols are just plain method names  For instance 1 + 2 stands for 1.+(2) Precedence rules: All letters | ^ & <  > =  ! : +  - *  /  % Page 33 class Complex(val re:Double, val im:Double) { def +(that: Complex) : Complex = {      new Complex(this.re + that.re,                   this.im + that.im)    }    override def toString() : String = {      re + (if (im < 0) "" else "+") + im +"i"    } } object Operators {   def main(args: Array[String]) {         val c1 = new Complex(1.0, 1.0)         val c2 = new Complex(2.0, 1.0)         println(c1+c2)   } } // => (3.0+2.0i)
Conversions Implicit converters allow Scala to automatically convert data types Suppose, you‘d like to introduce a mathematical notatation such as 10!  Using implicit type converters you can easily achieve this Page 34 object Factorial {   def fac(n: Int): BigInt =     if (n == 0) 1 else fac(n-1) * n   class Factorizer(n: Int) { def ! = fac(n)   } implicit def int2fac(n: Int) = new Factorizer(n) } import Factorial._ object ConvDemo extends Application { println("8! = " + (8!)) // 8 will be implicitly converted } // => 40320
Parameterized Types in Scala Classes, Traits, Functions may be parameterized with types In contrast to Java no wildcards permitted – parameter types must have names Variance specification allow to specify covariance and contravariance Page 35 trait MyTrait[S,T] {   def print(s:S, t:T) : String = "(" + s  + "," + t + ")" } class MyPair[S,T] (val s : S, val t : T)  extends MyTrait [S,T] {   override def toString() : String = print(s,t)	 } object Generics {   def main(args: Array[String]) { 	val m = new MyPair[Int,Int](1,1) 	printf(m.toString())   } } // => (1,1)
Small Detour to Variance and Covariance / Type Bounds If X[T] is a parameterized type and T an immutable type: X[T] is covariant in T if:	S subTypeOf T => X[S] subTypeOf  X[T] X[T] is contravariant in T if:  	S subTypeOf T => X[S] superTypeOf X[T] In Scala covariance is expressed as X[+T] and contravariance with X[-T] Covariance is not always what you want: Intuitively we could assign a set of apples to a set of fruits. However, to a set of fruits we can add an orange.  The original set of apples gets „corrupted“ this way Example List[+T]: Covariance means a List[Int] can be assigned to a List[Any] because Int is subtype of Any Upper/Lower Bounds may be specified: In the following example D must be supertype of S: 	def copy[S, D>:S](src: Array[S], dst: Array[D]) = { ... Page 36
Functional Aspects: Functions and Closures In Scala Functions are First-Class Citizens They can be  passed as arguments assigned to variables:           val closure={i:Int => i+42} Nested functions are also supported Page 37 object scalafunctions {   def add(left:Int,right:Int, code:Int=>Int)=   { var res = 0      for (i<-left to right) res += code(i)      res   }   def main(args: Array[String]) { println(add(0,10, i => i)) println(add(10,20, i => i % 2  ))   } } => 55 5
Functional Aspects: Call-by-Name If a parameterless closure is passed as an argument to a function, Scala will evaluate the argument when the argument is actually used This is in contrast to call-by-value arguments A similar effect can be achieved using lazy (value) evaluation:      lazy val = <expr>        Page 38 import java.util._ object CbNDemo { def fun(v: => Int) : Int = v   // v is a Call-by-Name Parameter def v() : Int = new Random().nextInt(1000)  def main(args:Array[String]) {    println( fun(v) )    println( fun(v) )    } } // => 123 <> 243
Functional Aspects: Currying (1) Currying means to transform a function with multiple arguments to a nested call of functions with one (or more) argument(s) def fun(i:Int)(j:Int) {}    (Int)=>(Int)=>Unit=<function1> Page 39 object scalafunctions {    def fun1(i:Int, j:Int) : Int = i + j def fun2(i:Int)(j:Int) : Int = i + j      def main(args: Array[String]) { 	println(fun1(2,3)) 	println(fun2(2){3}) 	println(fun2{2}{3} )    } }  // => 5 5 5
Functional Aspects: Currying (2) Currying helps increase readability Take foldleft as an example Page 40 FoldLeft Operator val x =  (0 /: (1 to 10)) { (sum, elem) => sum + elem } // 55  Carryover value for next iteration Function arguments Carryover value Collection For each iteration, foldleft passes the carry over value and the current collection element. We need to provide the operation to be applied This is collection which we iterate over This is the value that is updated in each iteration Think how this would be implemented in Java!
Positional Parameters If you use a parameter only once, you can use positional notation of parameters with _ (underscore) instead Page 41 object scalafunctions {  def main(args:Array[String]) { 	val seq= (1 to 10) 	println( (0 /: seq) { (sum, elem) => sum + elem } ) 	println( (0 /: seq) { _ + _ } )   }	 }
Using the features we can build new DSLs and additional features easily The following loop-unless example is from the Scala tutorial  Page 42 object TargetTest2 extends Application { def loop(body: => Unit): LoopUnlessCond =     new LoopUnlessCond(body) protected class LoopUnlessCond(body: => Unit) {     def unless(cond: => Boolean) {       body       if (!cond) unless(cond)     }   }   var i = 10    loop {     println("i = " + i)     i -= 1   } unless (i == 0) } We are calling loop with this body ... and invoking unless on the result
Functional Aspect: Partially Applied Functions If you only provide a subset of arguments to a function call, you actually retrieve a partially defined function Only the passed arguments are bound, all others are not In a call to a partially applied function you need to pass the unbound arguments All this is useful to leverage the DRY principle when passing the same arguments again and again Page 43 object scalafunctions {   def fun(a : Int, b : Int, c:Int) = a+b+c   def main(args: Array[String]) { val partialFun = fun(1,2,_:Int) 	  println( partialFun(3) ) // 6 	  println( partialFun(4) ) // 7 	} }
Functions Are Objects  Function: S => T  trait Function1[-S,+T] {      def apply(x:S):T    } Example:   (x: Int) => x * 2 -> new Function1[Int,Int] {      def apply(X:Int):Int = x * 2    } In Scala all function values are objects Basically, each function is identical to a class with an apply method Thus, you can even derive subclasses from functions Array is an example for this:  class Array [T] (length: Int )  extends (Int => T)  { def length: Int = ... Page 44
Functional Aspects: Pattern Matching Pattern matching allows to make a  pragmatic choice between various options Page 45 valaNumber = new Random().nextInt(6) + 1; aNumbermatch { case 6 => println("You got a 6") case 1 => println("You got a 1"); caseotherNumber => println("It is a " + otherNumber) }
Functional Aspects: Matching on Types It is also possible to differentiate by type: Page 46 object TypeCase {    def matcher(a: Any) { a match { 	   case i : Int if (i == 42) => println("42") 	   case j : Int => println("Another int") 	   case s : String => println(s) 	   case _  => println("Something else")         }    }    def main(args: Array[String]) { 	matcher(42) 	matcher(1) 	matcher("OOP") 	matcher(1.3)	    } } // => 41 <> 1  <> OOP <> Something else
Functional Aspects: Matching on Lists Lists can be easily used with Pattern Matching: Page 47 object ListCase {    def matcher(l: List[Int]) { l match { 	   case List(1,2,3,5,7) => println("Primes") 	   case List(_,_,_3,_) => println("3 on 3"); 	   case 1::rest => println("List with starting 1"); 	   case List(_*) => println("Other List");         }    }    def main(args: Array[String]) { 	matcher(List(1,2,3,5,7)) 	matcher(List(5,4,3,2)) 	matcher(List(1,4,5,6,7,8)); 	matcher(List(42))    } } => Primes <> 3 on 3 <> List with starting 1 <> Other List
Functional Aspects: Matching on Tuples So do Tuples: Page 48 object TupleCase {    def matcher(t : Tuple2[String,String]) { t match { 	   	case ("OOP",s) => println("OOP " + s)   		case ("Scala", s) => println("Scala " + s) 	   	case _ => println("Other Tuple")         }    }    def main(args: Array[String]) { 	matcher("OOP", "2010") 	matcher("Scala", "rocks"); 	matcher("A","B")    } } => OOP 2010 <> Scala rocks >cr> Other Tuple
Functional Aspects: Matching on Case Classes Case Classes are classes for which the compiler generates additional functionality to enable pattern matching, e.g., an apply() method: Page 49 sealed abstract class Shape // sealed => subclasses only in this source file case class Circle(val center: Point, val radius: Double) extends Shape case class Line(val pt1: Point, val pt2: Point) extends Shape case class Point (val x:Double, val y:Double){    override def toString() = "(" + x +"," + y + ")" } object CaseClasses {    def matcher(s : Shape) { s match { 	   case Circle(c, r) => println(“Circle“ :  + c +  “ “ + r) 	   case Line(p1, p2) => println("Line " + p1 + " : " + p2)  	   case _ => println("Unknown shape")         }    }    def main(args: Array[String]) { 	matcher(Circle(Point(1.0, 1.0), 2.0)) 	matcher(Line(Point(1.0, 1.0), Point(2.0, 2.0)))    } }
Functional Aspect: Extractors Extractors are objects with an unapply method used to match a value and partition it into constituents – an optional apply is used for synthesis Page 50 object EMail {   def apply(prefix: String, domain: String) = prefix + "@" + domain def unapply(s: String): Option[(String,String)] = {    val parts = s split "@"    if (parts.length == 2) Some(parts(0), parts(1)) else None   }  } object scalafunctions {  def main(args:Array[String]) {    val s = "michael.stal@siemens.com"    s match {       case EMail(user, domain) => println(user + " AT " + domain)      case _ => println("Invalid e-mail")    }   }	 }
Partial Functions  Partial Functions are not defined for all domain values Can be asked with isDefinedAt whether a domain value is accepted Example: Blocks of Pattern Matching Cases Page 51 trait PartialFunction[-D, +T]  extends (D => T) {   def isDefinedAt(x: D): Boolean }
Actors Actors have been introduced in the 1970s: the Actor model is a mathematical model of concurrent computationthat treats "actors" as the universal primitives of concurrent digital computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received. [Hewitt, 73] Page 52 Also available in Erlang, Axum, Io, Clojure Provided as library implementation in Scala (demonstrating Scala‘s capability of providing internal DSLs)
Actor Classes Class Actor requires to override act() which is the functionality executed by a thread You may also instantiate anonymous actors in a much more convenient way: Page 53 import scala.actors.Actor class VolcanextendsActor { def act() { println(“thinking ...")   } } object SpockRunner {   def main(args:Array[String]) = { valspock = new Volcan spock start   } } import scala.actors.Actor import Actor._ object SpockRunner {   def main(args:Array[String]) = { val spock = actor { 	println("thinking ...")     }   } }
Actors that communicate An actor is useless unless it cooperates with other actors Actors communicate via messages In Scala‘s actor library messages are processed in FIFO order Every actor owns an inbound and an outbound mailbox Page 54
Communicating Actors - Example Page 55 ! Note: react & receive have cousins with timeout arguments:   receiveWithin and reactWithin import scala.actors._ import Actor._ object Calculator extends Actor {   def fib(n: Int) : Int = { require(n >= 0) // this is a precondition  if (n <= 1) n else fib(n-2) + fib(n-1) }   def act() { loop {         react { // or receive if thread must preserve call-stack 	       case i:Int => actor {println("Fibonacci of "+i+" is "+fib(i))} 	       case s:String if (s == „exit")  => {println(„exit!"); exit} 	       case _ => println("received unknown message")          }      }   } } object ActorDemo extends Application {    Calculator.start // start Actor    for (i <- 0 to 30) Calculator ! i // here we send a msg to the actor Calculator ! "exit" }

Contenu connexe

Tendances

DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NETRasan Samarasinghe
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in javaGarik Kalashyan
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IAjit Nayak
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaRasan Samarasinghe
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language ComparisonRobert Bachmann
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence APIIlio Catallo
 

Tendances (20)

DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Javascript
JavascriptJavascript
Javascript
 
Kotlin
KotlinKotlin
Kotlin
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Scala
ScalaScala
Scala
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
Google06
Google06Google06
Google06
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 

En vedette

Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1Santiago Cortes
 
Web page evaluation
Web page evaluationWeb page evaluation
Web page evaluationsarabrownie
 
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòncông ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gònlenore810
 
Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1Alonzo Williams
 
Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”len398
 
Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)davidgbz
 
Los instrumento musicales
Los instrumento musicalesLos instrumento musicales
Los instrumento musicalesJoaquinLopez
 
La MúSica De La India
La MúSica De La IndiaLa MúSica De La India
La MúSica De La IndiaAna Benet
 
Souvenir kantor pajak profile
Souvenir kantor pajak profileSouvenir kantor pajak profile
Souvenir kantor pajak profileCera Production
 

En vedette (13)

Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1
 
Notka
NotkaNotka
Notka
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Web page evaluation
Web page evaluationWeb page evaluation
Web page evaluation
 
098765
098765098765
098765
 
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòncông ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
 
Santiago
SantiagoSantiago
Santiago
 
Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1
 
Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”
 
Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)
 
Los instrumento musicales
Los instrumento musicalesLos instrumento musicales
Los instrumento musicales
 
La MúSica De La India
La MúSica De La IndiaLa MúSica De La India
La MúSica De La India
 
Souvenir kantor pajak profile
Souvenir kantor pajak profileSouvenir kantor pajak profile
Souvenir kantor pajak profile
 

Similaire à Oop2010 Scala Presentation Stal

A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to ScalaRiccardo Cardin
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaPeter Maas
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?Sarah Mount
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 

Similaire à Oop2010 Scala Presentation Stal (20)

Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
Scala idioms
Scala idiomsScala idioms
Scala idioms
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 

Dernier

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Dernier (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Oop2010 Scala Presentation Stal

  • 1. Introduction toCoding in Scala is fun! OOP 2010 Dr. Michael Stal Michael.Stal@siemens.com
  • 2. Objectives of this Presentation Introduce core concepts of Scala Showing you the benefits of combining OO with functional programming Illustrating the language in a pragmatic way preferring code over theory But not to cover every available aspect or to cover aspects in full detail For instance, we won‘t cover Java/Scala Interop, Views, Equality Semantics, Unit Testing, Annotations Page 2
  • 3. Introduction Scala created by the team of Martin Odersky at EPFL „Scala“ means „Scalable Language“ „Scalable“ means: the same language concepts for programming in the small & large In Scala this is achieved in a pragmatic way by combining Object Oriented Programming with Functional Programming Scala is a statically typed language like Java All types are objects Page 3 Martin Odersky, Source: http://lamp.epfl.ch/~odersky/
  • 4. Object-Oriented & Functional Programming Object-Oriented Programming Abstraction using Classes and Interfaces Refinement using subtyping and inheritance (Remember the Liskov Substitution Principle!) Dynamics through polymorphism Functional Programming Higher Order Functions as First-Class Entities ADTs (Abstract Data Types) following algebraic conventions Pattern matching Parametric polymorphism (generic types) Page 4 SCALA
  • 5.
  • 9.
  • 10. Stairway to Heaven – First Steps using Scala This source code file may be compiled using scalac und run using scala: scalac HelloWorldMain.scala scala HelloWorldMain Note: the source file must be named like the main object to be executed You may run an interpreter by using the following command line instead scala HelloWorldMain.scala In this case you may also use plain Scala scripts (no classes or objects required) Or, even better, you might use an IDE like Idea, Netbeans, or Eclipse Page 7
  • 11. A more advanced example (1) (from Venkat Subramanian‘s book Programming Scala, pp.5) Page 8 import scala.actors._ import Actor._ val symbols = List( "AAPL", "GOOG", "IBM", "JAVA", "MSFT") val receiver = self val year = 2009 symbols.foreach { symbol => actor { receiver ! getYearEndClosing(symbol, year) } } val (topStock, highestPrice) = getTopStock(symbols.length) printf("Top stock of %d is %s closing at price %f", year, topStock, highestPrice) def getYearEndClosing(symbol : String, year : Int) = { val url = new java.net.URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=11&b=01&c=" + year + "&d=11&e=31&f=" + year + "&g=m") val data = io.Source.fromURL(url).mkString val price = data.split("")(1).split(",")(4).toDouble (symbol, price) } // .. to be continued
  • 12. A more advanced example (2)(from Venkat Subramanian‘s book Programming Scala, pp.5) Run this within interpreter mode scala TopScala.scala After the end of the talk return to this example and check whether you better understand it Page 9 // continued ... def getTopStock(count : Int) : (String, Double) = { (1 to count).foldLeft("", 0.0) { (previousHigh, index) => receiveWithin(10000) { case (symbol : String, price : Double) => if (price > previousHigh._2) (symbol, price) else previousHigh } } } // will result in => // Top stock of 2009 is GOOG closing at price 619,980000
  • 13. Scala Type Hierarchy Page 10 Scala uses a pure object-oriented type system Every value is an object Two types: values and references Any is parent class of all classes, Nothing subclass of all classes Basic types like in Java Source: Scala Reference Manual
  • 14. First Class Scala Page 11 born and id will be public fields Main constructor Classes in Scala contain fields, methods, types, constructors Visibility is public per default class CatID(val id : Int) //that's a whole class class Cat(val born: Int, val id: CatID) { private var miceEaten: Int = 0 def digested() = miceEaten def hunt(miceCaught: Int) { miceEaten += miceCaught } } object ScalaClasses { def main(args: Array[String]) { val id = new CatID(42) val tom = new Cat(2010, id) tom.hunt(3) tom hunt 2 println(“cat was born in “ + tom.born) println(tom.digested) } } // => 5 <> Tom was born in 2010 definition of methods No brackets required
  • 15. Class Constructors Page 12 class Complex (r : Double, i: Double) { println("Constructing a complex number") val re = r val im = i def this(r : Double) = this(r,0) override def toString = re + (if (im < 0) "-" + (-im) else "+" + im) + "*i" ... } Belongs to Primary constructor Auxilliary constructorsmust call primary
  • 16. Immutable and Mutable Objects Scala provides immutable objects (functional programming) but also mutable objects Immutability has many benefits Reduction of race conditions in concurrent programs Protection against unwanted modification Scala provides mutable & immutable versions of collection types Mutable objects are important to address objects that are supposed to change their state, but use them with care Page 13 class Person(var name: String) object ImmutabilityDemo { def main(args:Array[String]) = { val s = "Michael" s = "Bill" // error var t = "Michael“ // t variable t = "Bill" // ok val c = new Person("Bill") c = new Person("Tom") // error // ok - c itself unchanged: c.name = "Tom" } }
  • 17. Inheritance In Scala classes can be derived from at most one base class Classes may be abstract You need to indicate whether you override inherited methods Page 14 abstractclass Shape { type Identifier = Int // defining types def getID() : Identifier = 42 def draw() : String // abstract method } class Circle (val cx: Double, val cy: Double, val r: Double) extends Shape { val id : Identifier = getID() override def draw() : String = "I am a Circle" }
  • 18. Companion Objects and Standalone Objects We already saw standalone objects Objects are singletons If you need static fields or methods for a class, introduce a companion class with the same name Convention: apply() methods may be provided as factory methods Page 15 class Cat private (val born : Int, val id: CatID) { ... private def this(id: CatID) = this(2010, id) ... } // all constructors are private object Cat { // this is the companion object of Cat def apply(born: Int, id: CatID) = new Cat(born, id) def apply(id: CatID) = new Cat(id) // factory method def whatCatsDo() = "Sleep, eat, play" } object ScalaClasses { // Standalone Object def main(args: Array[String]) { val id = new CatID(43) val pussy = Cat(id) // no new required println("Pussy was born in " + pussy.born) println(Cat.whatCatsDo) // like static in Java } }
  • 19. Application Base Class For experimenting with Scala use the base class Application Just compile this with: scalac ObjDemo.scala And run it with: scala ObjDemo Useful abbreviation if you do not need to deal with command line arguments Page 16 Inheritance object ObjDemoextends Application { val s: String = "Michael" println(s) // => Michael }
  • 20. Traits Classes and instances may mix-in additional functionality using traits Traits represent an abstraction between interfaces and classes Using traits we can easily live with the single-inheritance restriction You may use also traits via anonymous classes: val x = new Identity{} x.name = "UFO" println(x.whoAmI) Page 17 trait Identity { var name: String="" def whoAmI() : String = name } class Person extends Identity class Animal object TraitDemo { def main(args:Array[String]) = { val p = new Person p.name = "Michael" println(p.whoAmI) val a = new Animal with Identity a.name = "Kittie" println(a.whoAmI) } } // => Michael <> Kittie
  • 21. Traits and Virtual Super: Inheritance Linearization Page 18 abstract class Processor { def process() } trait Compressor extends Processor { // trait only applicable to Processor subclass abstract override def process() = { println("I am compressing"); super.process } } trait Encryptor extends Processor { // only applicable to Processor subclass abstract override def process() = { println("I am encrypting"); super.process} } class SampleProcessor extends Processor { // subclass of Processor override def process() = println("I am a Sample Processor") } object traitsample2 { def main(args:Array[String]) = { // mixing in a trait to an object: val proc1 = new SampleProcessor with Compressor with Encryptor proc1.process// Encryptor.process=>Compressor.process } // => SampleProcessor.process } Note: abstract override for a trait method means the actual subclass of Processor will provide a concrete implementation of that method!
  • 22. Scala Basics: if Statements If statements are expressions themselves, i.e. they have values Page 19 import java.util._ if (1 + 1 == 3) println(“strange world”) else { println(“everything’s ok”) } val res = if ((new Random().nextInt(6) + 1) == 6) "You win!" else "You lose!"
  • 23. Scala Basics: for Comprehensions (1) A for comprehension is like a for loop. It lets you traverse a collection, return every object in a temporary variable which is then passed to an expression. You may also specify nested iterations: You can specify filters for the collection elements Page 20 val aList = List(1,2,3,4,5,6) for (i <- aList) println(i) // => 1 <> 2 ... val dogs = Set("Lassie", "Lucy", "Rex", "Prince"); for (a <- dogs if a.contains("L")) println(a) // => “Lassie” <> “Lucy”
  • 24. Scala Basics: for Comprehensions (2) Yield allows to create new collections in a for comprehension: You can specify filters for the collection elements Page 21 var newSet = for { a <- dogs if a.startsWith("L") } yield a println(newSet) // Set(Lassie, Lucy) for { i <- List(1,2,3,4,5,6) j = i * 2 // new variable j defined } println(j) // => 2 <> 4 <> 6 ...
  • 25. Scala Basics: Other loops Scala supports while and do-while loops But generator expressions such as (1 to 6) incl. 6 or (1 until 6) excl. 6 together with for make this much easier Note: The reason this works is a conversion to RichInt where to is defined as a method that returns an object of type Range.Inclusive, an inner class of Range implementing for comprehensions Page 22 var i = 1 while (i <= 6) { println(i) i += 1 } // = 1 <> 2 <> 3 ... for (i <- 1 to 6) println(i)
  • 26. Scala Basics: Exception handling try-catch-finally available in Scala but throws isn‘t catching checked exceptions is optional! catch-order important as in Java, C++ or C# Page 23 def temperature(f: Double) { if (f < 0) throw new IllegalArgumentException() } try { println("acquiring resources") temperature(-5) } catch { case ex: IllegalArgumentException => println("temperatur < 0!") case _ => println("unexpected problem") } finally { println("releasing resources") }
  • 27. Inner Classes You may define inner classes as in Java Special notation (<name> =>) for referring to outer class this from an inner class: you might also use <outerclass>.this instead Page 24 class Element (val id: String){ elem => class Properties { // inner class type KV = Tuple2[String, Any] var props: List[KV] = Nil def add(entry: KV) { props = entry :: props } override def toString = { var s: String = "" for (p <- properties.props) s = s + p +"" s } } override def toString = "ID = " + id + "" + properties val properties = new Properties } object InnerClassDemo extends Application { val e = new Element("Window") e.properties.add("Color", "Red") e.properties.add("Version", 42) println(e.toString) }
  • 28.
  • 29. import p.{x => a} the member x of p renamed as a.
  • 30. import p.{x, y} the members x and y of p.
  • 31.
  • 32. Advanced Types: Sets Collection Type: Set Page 27 object SetDemo { def main(args:Array[String]) { val s1 = Set[Int](1,2,3,4,5) // we could also use = Set(1,2,3,4,5) val s2 = Set[Int](2,3,5,7) println(s2.contains(3)) // => true val s3 = s1 ++ s2 // union println(s3) // => Set(5,7,3,1,4,2) vals4 = s1 & s2 // intersection: in earlier versions ** println(s4) // Set(5,3,2) } }
  • 33. Advanced Types: Maps Collection Type: Map Page 28 object MapDemo { def main(args:Array[String]) { val m1 = Map[Int, String](1 -> "Scala", 2->"Java", 3->"Clojure") valm2 = m1 + (4 -> "C#") // add entry println(m2 + " has size " + m2.size) //=> Map(1->Scala,…) has size 4 println(m1(1)) // => Scala val m3 = m2 filter { element => val (key, value) = element (value contains "a") } println(m3) // => Map(1->Scala, w->Java) } }
  • 34. Advanced Types: Options object DayOfWeek extends Enumeration { val Monday = Value("Monday") //argument optional val Sunday = Value("Sunday") //argument optional } import DayOfWeek._ object OptionDemo { def whatIDo(day: DayOfWeek.Value) : Option[String] = { day match { case Monday => Some("Working hard") case Sunday => None } } def main(args:Array[String]) { println(whatIDo(DayOfWeek.Monday)) println(whatIDo(DayOfWeek.Sunday)) } //=> Some(„Working Hard“) <> None } The Option type helps dealing with optional values For instance, a search operation might return a result or nothing We are also introducing Enumerationtypes Page 29
  • 35. Advanced Types: Regular Expressions Type: Regex introduces well-known regular expressions Page 30 With this syntax strings remain formatted as specified and escape sequences are not required object RegDemo { def main(args:Array[String]) { val pattern = """""".r val sentence = “X was born on 01.01.2000 ?" println (pattern findFirstIn sentence) // => Some(01.01.2000) } } Note: the „r“ in “““<string>“““.r means: regular expression
  • 36. Advanced Types: Tuples Tuples combine fixed number of Elements of various types Thus, you are freed from creating heavy-weight classes for simple aggregates Page 31 println( (1, "Douglas Adams", true) ) def goodBook = { ("Douglas Adams", 42, "Hitchhiker's Guide") } println ( goodBook._3 ) // get third element // => (1, Douglas Adams, true) // => Hitchhiker‘s Guide
  • 37. Advanced Types: Arrays Arrays hold sequences of elements Access very efficient Page 32 val a1 = new Array[Int](5) // initialized with zeros val a2 = Array(1,2,3,4,5) // initialized with 1,2,3,4,5 println( a2(1) ) // => 2 a2(1) = 1 // => Array (1,1,3,4,5) Note: In Scala the assignment operator = does not return a reference to the left variable (e.g., in a = b). Thus, the following is allowed in Java but not in Scala: a = b = c
  • 38. Smooth Operator In Scala operator symbols are just plain method names For instance 1 + 2 stands for 1.+(2) Precedence rules: All letters | ^ & < > = ! : + - * / % Page 33 class Complex(val re:Double, val im:Double) { def +(that: Complex) : Complex = { new Complex(this.re + that.re, this.im + that.im) } override def toString() : String = { re + (if (im < 0) "" else "+") + im +"i" } } object Operators { def main(args: Array[String]) { val c1 = new Complex(1.0, 1.0) val c2 = new Complex(2.0, 1.0) println(c1+c2) } } // => (3.0+2.0i)
  • 39. Conversions Implicit converters allow Scala to automatically convert data types Suppose, you‘d like to introduce a mathematical notatation such as 10! Using implicit type converters you can easily achieve this Page 34 object Factorial { def fac(n: Int): BigInt = if (n == 0) 1 else fac(n-1) * n class Factorizer(n: Int) { def ! = fac(n) } implicit def int2fac(n: Int) = new Factorizer(n) } import Factorial._ object ConvDemo extends Application { println("8! = " + (8!)) // 8 will be implicitly converted } // => 40320
  • 40. Parameterized Types in Scala Classes, Traits, Functions may be parameterized with types In contrast to Java no wildcards permitted – parameter types must have names Variance specification allow to specify covariance and contravariance Page 35 trait MyTrait[S,T] { def print(s:S, t:T) : String = "(" + s + "," + t + ")" } class MyPair[S,T] (val s : S, val t : T) extends MyTrait [S,T] { override def toString() : String = print(s,t) } object Generics { def main(args: Array[String]) { val m = new MyPair[Int,Int](1,1) printf(m.toString()) } } // => (1,1)
  • 41. Small Detour to Variance and Covariance / Type Bounds If X[T] is a parameterized type and T an immutable type: X[T] is covariant in T if: S subTypeOf T => X[S] subTypeOf X[T] X[T] is contravariant in T if: S subTypeOf T => X[S] superTypeOf X[T] In Scala covariance is expressed as X[+T] and contravariance with X[-T] Covariance is not always what you want: Intuitively we could assign a set of apples to a set of fruits. However, to a set of fruits we can add an orange. The original set of apples gets „corrupted“ this way Example List[+T]: Covariance means a List[Int] can be assigned to a List[Any] because Int is subtype of Any Upper/Lower Bounds may be specified: In the following example D must be supertype of S: def copy[S, D>:S](src: Array[S], dst: Array[D]) = { ... Page 36
  • 42. Functional Aspects: Functions and Closures In Scala Functions are First-Class Citizens They can be passed as arguments assigned to variables: val closure={i:Int => i+42} Nested functions are also supported Page 37 object scalafunctions { def add(left:Int,right:Int, code:Int=>Int)= { var res = 0 for (i<-left to right) res += code(i) res } def main(args: Array[String]) { println(add(0,10, i => i)) println(add(10,20, i => i % 2 )) } } => 55 5
  • 43. Functional Aspects: Call-by-Name If a parameterless closure is passed as an argument to a function, Scala will evaluate the argument when the argument is actually used This is in contrast to call-by-value arguments A similar effect can be achieved using lazy (value) evaluation: lazy val = <expr> Page 38 import java.util._ object CbNDemo { def fun(v: => Int) : Int = v // v is a Call-by-Name Parameter def v() : Int = new Random().nextInt(1000) def main(args:Array[String]) { println( fun(v) ) println( fun(v) ) } } // => 123 <> 243
  • 44. Functional Aspects: Currying (1) Currying means to transform a function with multiple arguments to a nested call of functions with one (or more) argument(s) def fun(i:Int)(j:Int) {} (Int)=>(Int)=>Unit=<function1> Page 39 object scalafunctions { def fun1(i:Int, j:Int) : Int = i + j def fun2(i:Int)(j:Int) : Int = i + j def main(args: Array[String]) { println(fun1(2,3)) println(fun2(2){3}) println(fun2{2}{3} ) } } // => 5 5 5
  • 45. Functional Aspects: Currying (2) Currying helps increase readability Take foldleft as an example Page 40 FoldLeft Operator val x = (0 /: (1 to 10)) { (sum, elem) => sum + elem } // 55 Carryover value for next iteration Function arguments Carryover value Collection For each iteration, foldleft passes the carry over value and the current collection element. We need to provide the operation to be applied This is collection which we iterate over This is the value that is updated in each iteration Think how this would be implemented in Java!
  • 46. Positional Parameters If you use a parameter only once, you can use positional notation of parameters with _ (underscore) instead Page 41 object scalafunctions { def main(args:Array[String]) { val seq= (1 to 10) println( (0 /: seq) { (sum, elem) => sum + elem } ) println( (0 /: seq) { _ + _ } ) } }
  • 47. Using the features we can build new DSLs and additional features easily The following loop-unless example is from the Scala tutorial Page 42 object TargetTest2 extends Application { def loop(body: => Unit): LoopUnlessCond = new LoopUnlessCond(body) protected class LoopUnlessCond(body: => Unit) { def unless(cond: => Boolean) { body if (!cond) unless(cond) } } var i = 10 loop { println("i = " + i) i -= 1 } unless (i == 0) } We are calling loop with this body ... and invoking unless on the result
  • 48. Functional Aspect: Partially Applied Functions If you only provide a subset of arguments to a function call, you actually retrieve a partially defined function Only the passed arguments are bound, all others are not In a call to a partially applied function you need to pass the unbound arguments All this is useful to leverage the DRY principle when passing the same arguments again and again Page 43 object scalafunctions { def fun(a : Int, b : Int, c:Int) = a+b+c def main(args: Array[String]) { val partialFun = fun(1,2,_:Int) println( partialFun(3) ) // 6 println( partialFun(4) ) // 7 } }
  • 49. Functions Are Objects Function: S => T  trait Function1[-S,+T] { def apply(x:S):T } Example: (x: Int) => x * 2 -> new Function1[Int,Int] { def apply(X:Int):Int = x * 2 } In Scala all function values are objects Basically, each function is identical to a class with an apply method Thus, you can even derive subclasses from functions Array is an example for this: class Array [T] (length: Int ) extends (Int => T) { def length: Int = ... Page 44
  • 50. Functional Aspects: Pattern Matching Pattern matching allows to make a pragmatic choice between various options Page 45 valaNumber = new Random().nextInt(6) + 1; aNumbermatch { case 6 => println("You got a 6") case 1 => println("You got a 1"); caseotherNumber => println("It is a " + otherNumber) }
  • 51. Functional Aspects: Matching on Types It is also possible to differentiate by type: Page 46 object TypeCase { def matcher(a: Any) { a match { case i : Int if (i == 42) => println("42") case j : Int => println("Another int") case s : String => println(s) case _ => println("Something else") } } def main(args: Array[String]) { matcher(42) matcher(1) matcher("OOP") matcher(1.3) } } // => 41 <> 1 <> OOP <> Something else
  • 52. Functional Aspects: Matching on Lists Lists can be easily used with Pattern Matching: Page 47 object ListCase { def matcher(l: List[Int]) { l match { case List(1,2,3,5,7) => println("Primes") case List(_,_,_3,_) => println("3 on 3"); case 1::rest => println("List with starting 1"); case List(_*) => println("Other List"); } } def main(args: Array[String]) { matcher(List(1,2,3,5,7)) matcher(List(5,4,3,2)) matcher(List(1,4,5,6,7,8)); matcher(List(42)) } } => Primes <> 3 on 3 <> List with starting 1 <> Other List
  • 53. Functional Aspects: Matching on Tuples So do Tuples: Page 48 object TupleCase { def matcher(t : Tuple2[String,String]) { t match { case ("OOP",s) => println("OOP " + s) case ("Scala", s) => println("Scala " + s) case _ => println("Other Tuple") } } def main(args: Array[String]) { matcher("OOP", "2010") matcher("Scala", "rocks"); matcher("A","B") } } => OOP 2010 <> Scala rocks >cr> Other Tuple
  • 54. Functional Aspects: Matching on Case Classes Case Classes are classes for which the compiler generates additional functionality to enable pattern matching, e.g., an apply() method: Page 49 sealed abstract class Shape // sealed => subclasses only in this source file case class Circle(val center: Point, val radius: Double) extends Shape case class Line(val pt1: Point, val pt2: Point) extends Shape case class Point (val x:Double, val y:Double){ override def toString() = "(" + x +"," + y + ")" } object CaseClasses { def matcher(s : Shape) { s match { case Circle(c, r) => println(“Circle“ : + c + “ “ + r) case Line(p1, p2) => println("Line " + p1 + " : " + p2) case _ => println("Unknown shape") } } def main(args: Array[String]) { matcher(Circle(Point(1.0, 1.0), 2.0)) matcher(Line(Point(1.0, 1.0), Point(2.0, 2.0))) } }
  • 55. Functional Aspect: Extractors Extractors are objects with an unapply method used to match a value and partition it into constituents – an optional apply is used for synthesis Page 50 object EMail { def apply(prefix: String, domain: String) = prefix + "@" + domain def unapply(s: String): Option[(String,String)] = { val parts = s split "@" if (parts.length == 2) Some(parts(0), parts(1)) else None } } object scalafunctions { def main(args:Array[String]) { val s = "michael.stal@siemens.com" s match { case EMail(user, domain) => println(user + " AT " + domain) case _ => println("Invalid e-mail") } } }
  • 56. Partial Functions Partial Functions are not defined for all domain values Can be asked with isDefinedAt whether a domain value is accepted Example: Blocks of Pattern Matching Cases Page 51 trait PartialFunction[-D, +T] extends (D => T) { def isDefinedAt(x: D): Boolean }
  • 57. Actors Actors have been introduced in the 1970s: the Actor model is a mathematical model of concurrent computationthat treats "actors" as the universal primitives of concurrent digital computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received. [Hewitt, 73] Page 52 Also available in Erlang, Axum, Io, Clojure Provided as library implementation in Scala (demonstrating Scala‘s capability of providing internal DSLs)
  • 58. Actor Classes Class Actor requires to override act() which is the functionality executed by a thread You may also instantiate anonymous actors in a much more convenient way: Page 53 import scala.actors.Actor class VolcanextendsActor { def act() { println(“thinking ...") } } object SpockRunner { def main(args:Array[String]) = { valspock = new Volcan spock start } } import scala.actors.Actor import Actor._ object SpockRunner { def main(args:Array[String]) = { val spock = actor { println("thinking ...") } } }
  • 59. Actors that communicate An actor is useless unless it cooperates with other actors Actors communicate via messages In Scala‘s actor library messages are processed in FIFO order Every actor owns an inbound and an outbound mailbox Page 54
  • 60. Communicating Actors - Example Page 55 ! Note: react & receive have cousins with timeout arguments: receiveWithin and reactWithin import scala.actors._ import Actor._ object Calculator extends Actor { def fib(n: Int) : Int = { require(n >= 0) // this is a precondition if (n <= 1) n else fib(n-2) + fib(n-1) } def act() { loop { react { // or receive if thread must preserve call-stack case i:Int => actor {println("Fibonacci of "+i+" is "+fib(i))} case s:String if (s == „exit") => {println(„exit!"); exit} case _ => println("received unknown message") } } } } object ActorDemo extends Application { Calculator.start // start Actor for (i <- 0 to 30) Calculator ! i // here we send a msg to the actor Calculator ! "exit" }
  • 61. Processing XML in Scala Scala can directly handle XML With package scala.xml we can read, parse, create and store XML documents XPath like query syntax Page 56 import scala.xml._ // in our example not required object XMLDemo extends Application { val x : scala.xml.Elem = <conferences> <conference name="OOP"> <year> 2010 </year> </conference> <conference name="SET"> <year> 2010 </year> </conference> </conferences> var conferenceNodes = x "conference„ // get all conference nodes for (c <- conferenceNodes) println( cquot;@name“ ) // get attribute } // => OOP <> SET
  • 62. Accessing the Web with Scala You may use a mixture of Java and Scala code to access the Web Suppose, you‘d like to read a Web Page Here is an example how this might work Page 57 import java.net._ object WebDemo { def main(args: Array[String]) { require(args.length == 1) // we assume an URL was passed at the // command line: val url = new URL(args(0)) // make URL // read web page stream and convert // result to a string: val page = io.Source.fromURL(url).mkString println(page) // display result } }
  • 63. Scala Installation & Use Download distribution from http://www.scala-lang.org You may use Scala Compilers: scalac and fsc Eclipse, JetBrains, NetBeans Plug-In REPL (Read-Eval-Print-Loop) shell: scala I have tested these on Windows {XP, Vista} as well as Mac OS X (Snow Leopard) Or a Web site for evaluating Scala scripts: http://www.simplyscala.com/ If you are interested in a Web Framework based on Scala use Lift 1.0: http://liftweb.net/ Page 58
  • 64. Summary Scala combines the best of two worlds: OO and Functional Programming It runs on the JVM and offers Java interoperability Actor library helps dealing with complexity of concurrent programming Scala programs are compact and concise => big productivity boost possible Upcoming v2.8 will offer additional benefits such as named & default arguments Scala is no island - many further tools and frameworks (e.g., Lift) available Coding with Scala is fun - Try it yourself! Page 59
  • 65. Books: My Recommendations M. Odersky, L. Spoon, B. Venners: Programming in Scala: A Comprehensive Step-by-step Guide (Paperback), Artima Inc; 1st edition (November 26, 2008) – The Language Reference! V. Subramanian: Programming Scala: Tackle Multi-Core Complexity on the Java Virtual Machine (Pragmatic Programmers) (Paperback), Pragmatic Bookshelf (July 15, 2009) D. Wempler, A. Paine: Programming Scala: Scalability = Functional Programming + Objects (Animal Guide) (Paperback), O'Reilly Media; 1st edition (September 25, 2009) A lot of additional books available in the meantime. Page 60