SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
An Introduction to Scala
Blending OO and Functional Paradigms




               Miles Sabin, Chuusai Ltd.
                http://www.chuusai.com/

           http://uk.linkedin.com/in/milessabin
                  http://twitter.com/milessabin
Outline
●
    Background
●
    Functional Features
●
    Object-Oriented Features
●
    Selected Highlights
●
    Tools and Frameworks
●
    Roadmap
Background
●
    Designed by Martin Odersky (Pizza, GJ and
    Java 5) of EPFL as the successor to Funnel
●
    Objectives,
    ●
        Blend object-oriented and functional styles
    ●
        Seamless interoperability with Java (and .Net?)
●
    Project started in 2003
    ●
        First public release in 2004
    ●
        Currently at 2.7.7
    ●
        2.8 release due very soon
Scala is the Future of Java
●
    Scala can be thought of as a superset of
    current Java
    ●
        It has all the object-oriented features of
        current Java (some in a slightly different and
        improved form)
    ●
        It already has many of the most desirable
        proposed extensions to Java (eg. true closures)
●
    Nevertheless, it compiles to Java bytecode
    ●
        Flawless interopability with Java, leverages the
        mature Hotspot JIT
Interoperbility with Java
●
    There are many alternative JVM languages.
    Some also strongly “Java-compatible”
    ●
        Close source and binary mapping to Java
        –   Scala, Groovy, JavaFX, AspectJ
●
    This holds out the prospect that most Java
    tools, libraries and frameworks will Just
    Work, or work with only minor adaptation
●
    Additional promise of gradual migration of
    existing Java projects
Who's Using It?
●
    A rapidly growing list of companies and
    projects,
    ●
        Twitter (infrastructure)
    ●
        LinkedIn (analytics, infrastructure)
    ●
        EDF Trading (analytics, infrastructure)
    ●
        Sony Pictures Imageworks (infrastructure)
    ●
        SAP/Siemens (ESME, enterprise messaging)
    ●
        Novell (Pulse, enterprise messaging)
Why Mix OO and FP?
●
    Each has complementary strengths —
    ●
        OO provides excellent support for,
        –   Subtyping and inheritance
        –   Modular components
        –   Classes as partial abstractions
    ●
        FP provides excellent support for,
        –   Higher order functions
        –   ADTs, structural recursion and pattern matching
        –   Parametric polymorphism
●
    They've been converging for a while now
Scala has a REPL
●
    Common in scripting and functional
    languages
●
    Great for exploratory programming
●
    We'll be using it as we go along
Scala Cleans Up Java Syntax
●
    Semi-colons are optional, equals is ==
●
    All statements are expressions and have a
    value
●
    Type inference eliminates the most
    annoying explicit typing annotations
●
    Case-classes have minimal boilerplate
●
    Closures and by name arguments allow
    libraries to define specialized control
    structures
Statically Typed with Inference
●
    All definitions must have a static type
      val m : Map[Int, String]

●
    However these types are typically inferred
      scala> val m = Map(1 -> "one", 2 -> "two")
      m : Map[Int, String] = Map(1 -> one, 2 -> two)

●
    Method return types are also inferred
      scala> def twice(i : Int) = i*2
      twice: (i: Int)Int

    Argument types must be explicit, also the
    return types for recursive functions
First-Class Functions
●
    Scala allows the definition of functions
    def plusOne(x : Int) = x+1

●
    Functions can be arguments and results
    def applyTwice(x : Int, f : Int => Int) = f(f(x))
    applyTwice(3, plusOne) // == 5

●
    Can be anonymous and close over their
    environment
    def twice(f : Int => Int) = (x : Int) => f(f(x))
    twice(plusOne)(3) // == 5

●
    Function literal syntax is concise
    twice(_+1)(3) // == 5
Higher-Order Functions
●
    Higher-order functions are used
    extensively in Scala's standard library
    List(1, 2, 3).map(_*2) // == List(2, 4, 6)

    List(1, 2, 3, 4).find(_%2 == 0) // Some(2)

    List(1, 2, 3, 4).filter(_%2 == 0) // List(2, 4)

    def recip(x : Int) = if(x == 0) None else Some(1.0/x)

    scala> List(0, 1, 2, 3).flatMap(recip)
    res0: List[Int] = List(1.0, 0.5, 0.3333333333333333)
For Comprehensions
●
    Scala's “for comprehensions” capture
    common patterns of use of map, flatMap
    and filter
      val l1 = List(0, 1)
      val l2 = List(2, 3)

      scala> for (x <- l1; y <- l2) yield (x, y)
      res0: List[(Int, Int)] = List((0,2), (0,3), (1,2), (1,3))

    The for expression desugars to,
      l.flatMap(x => l2.map(y => (x, y))

●
    These patterns are the monad laws for the
    subject type
Case Classes are Lightweight
●
    Eliminate a lot of the boilerplate associated
    with Java implementations of simple data
    types
      public class User {
        private final String name;
        private final String pass;
        public User(String name_, String pass_) {
          name = name_;
          pass = pass_;
        }
        public boolean equals(Object other) {
          // Stuff ...
        }
        public int hashCode() {
          // More stuff ...
        }
      }
Case Classes are Lightweight
●
    The Scala equivalent
      case class User(name : String, pass : String)

●
    Accessors, equals, hashCode and toString
    are provided automatically
●
    “new” is optional
      val joe = User("Joe Bloggs", "<secret>")

●
    “Copy with changes” supports immutable
    functional objects
      val joeUpdated = joe.copy(pass = "<still secret>")
Pattern Matching
●
    Case classes model ADTs from functional
    languages and support pattern matching
      sealed trait Tree[T]
      case class Leaf[T](elem : T) extends Tree[T]
      case class Node[T](left : Tree[T], right : Tree[T])

      val t = Node(Node(Leaf("bar"), Leaf("baz")), Leaf("foo"))

      def find[T](tree : Tree[T], elem : T) : Boolean =
        tree match {
          case Node(l, r)   => find(l, elem) || find(r, elem)
          case Leaf(`elem`) => true
          case _ => false
        }

●
    Matching is the inverse of construction
The Option Type
●
    “Null References: The Billion Dollar
    Mistake” — Tony Hoare
●
    Scala provides a safe alternative
      scala> List(1, 2, 3) find (_ == 2)
      res0: Option[Int] = Some(2)

      scala> List(1, 2, 3) find (_ == 4)
      res0: Option[Int] = None

●
    Option interacts nicely with matching
      List(1, 2, 3) find (_ == 2) match {
        case Some(i) => println("Found "+i)
        case None => println("Not found")
      }
For Comprehensions Again
●
    Option implements map, flatMap and Filter
    so works nicely with for comprehensions
      def goodPair(x : Int, y : Int) =
        for(fst <- recip(x); snd <- recip(y))
          yield (x, y)

      scala> goodPair(1, 2)
      res0: Option[(Int, Int)] = Some((1,2))

      scala> goodPair(1, 0)
      res0: Option[(Int, Int)] = None

●
    Using Option rather than null has clear
    benefits when used in this way
Tools and Frameworks
●
    Most Java tools and frameworks work with
    Scala Out Of The Box
●
    Testing frameworks —
    ●
        Specs, ScalaTest, ScalaCheck
●
    Web frameworks —
    ●
        Lift
    ●
        Wicket and Play recently added Scala support
●
    IDE support — the big three (Eclipse,
    Netbeans, IDEA) all actively developed
Roadmap
●
    Upcoming releases,
    ●
        Beta of 2.8 now available
    ●
        First 2.8 Release Candidate expected in March
    ●
        2.8 Final expected June/July
●
    Subsequent 2.8-series releases will
    continue current exploratory work,
    ●
        Type specialization (still needs library support)
    ●
        Continuations (currently a compiler plugin)
    ●
        Linear/immutable/non-null types
Find Out More
●
    Scala's home at EPFL
    http://www.scala-lang.org
    ●
        See also the scala and scala-user mailing list
●
    The London Scala Users' Group
    http://www.meetup.com/london-scala
●
    Publications
    ●
        Programming in Scala
        Odersky, Venners and Spoon
    ●
        Programming in Scala
        Wampler and Payne
An Introduction to Scala
Blending OO and Functional Paradigms




               Miles Sabin, Chuusai Ltd.
                http://www.chuusai.com/

           http://uk.linkedin.com/in/milessabin
                  http://twitter.com/milessabin

Mais conteúdo relacionado

Mais procurados

An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Clojure talk at Münster JUG
Clojure talk at Münster JUGClojure talk at Münster JUG
Clojure talk at Münster JUGAlex Ott
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresqueBret McGuire
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmerselliando dias
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmerselliando dias
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorialDima Statz
 
Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Erik Schmiegelow
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaStratio
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Scala overview
Scala overviewScala overview
Scala overviewSteve Min
 
The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論scalaconfjp
 
Clojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVMClojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVMelliando dias
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 

Mais procurados (19)

An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Clojure talk at Münster JUG
Clojure talk at Münster JUGClojure talk at Münster JUG
Clojure talk at Münster JUG
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmers
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Clojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp ProgrammersClojure - An Introduction for Lisp Programmers
Clojure - An Introduction for Lisp Programmers
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorial
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Scala intro for Java devs 20150324
Scala intro for Java devs 20150324
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Scala overview
Scala overviewScala overview
Scala overview
 
The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論The Evolution of Scala / Scala進化論
The Evolution of Scala / Scala進化論
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Clojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVMClojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVM
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 

Semelhante a An Introduction to Scala - Blending OO and Functional Paradigms

BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaBasuk
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumNgoc Dao
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark Summit
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinayViplav Jain
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistpmanvi
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuHavoc Pennington
 

Semelhante a An Introduction to Scala - Blending OO and Functional Paradigms (20)

BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Develop realtime web with Scala and Xitrum
Develop realtime web with Scala and XitrumDevelop realtime web with Scala and Xitrum
Develop realtime web with Scala and Xitrum
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Scala final ppt vinay
Scala final ppt vinayScala final ppt vinay
Scala final ppt vinay
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
Yes scala can!
Yes scala can!Yes scala can!
Yes scala can!
 

Mais de Miles Sabin

Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...Miles Sabin
 
Eclipsecon 2010 - Scala Support in Eclipse
Eclipsecon 2010 - Scala Support in EclipseEclipsecon 2010 - Scala Support in Eclipse
Eclipsecon 2010 - Scala Support in EclipseMiles Sabin
 
Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?
Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?
Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?Miles Sabin
 
What's new in Scala and the Scala IDE for Eclipse for 2.8.0
What's new in Scala and the Scala IDE for Eclipse for 2.8.0What's new in Scala and the Scala IDE for Eclipse for 2.8.0
What's new in Scala and the Scala IDE for Eclipse for 2.8.0Miles Sabin
 
JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?
JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?
JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?Miles Sabin
 
The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0
The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0
The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0Miles Sabin
 

Mais de Miles Sabin (6)

Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
 
Eclipsecon 2010 - Scala Support in Eclipse
Eclipsecon 2010 - Scala Support in EclipseEclipsecon 2010 - Scala Support in Eclipse
Eclipsecon 2010 - Scala Support in Eclipse
 
Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?
Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?
Scala Support in Eclipse - Monkey-patching the JDT for fun and profit?
 
What's new in Scala and the Scala IDE for Eclipse for 2.8.0
What's new in Scala and the Scala IDE for Eclipse for 2.8.0What's new in Scala and the Scala IDE for Eclipse for 2.8.0
What's new in Scala and the Scala IDE for Eclipse for 2.8.0
 
JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?
JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?
JVM Languages Support in Eclipse - Monkey-patching the JDT for fun and profit?
 
The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0
The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0
The Scala IDE for Eclipse - Retrospect and Prospect for 2.8.0
 

An Introduction to Scala - Blending OO and Functional Paradigms

  • 1. An Introduction to Scala Blending OO and Functional Paradigms Miles Sabin, Chuusai Ltd. http://www.chuusai.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin
  • 2. Outline ● Background ● Functional Features ● Object-Oriented Features ● Selected Highlights ● Tools and Frameworks ● Roadmap
  • 3. Background ● Designed by Martin Odersky (Pizza, GJ and Java 5) of EPFL as the successor to Funnel ● Objectives, ● Blend object-oriented and functional styles ● Seamless interoperability with Java (and .Net?) ● Project started in 2003 ● First public release in 2004 ● Currently at 2.7.7 ● 2.8 release due very soon
  • 4. Scala is the Future of Java ● Scala can be thought of as a superset of current Java ● It has all the object-oriented features of current Java (some in a slightly different and improved form) ● It already has many of the most desirable proposed extensions to Java (eg. true closures) ● Nevertheless, it compiles to Java bytecode ● Flawless interopability with Java, leverages the mature Hotspot JIT
  • 5. Interoperbility with Java ● There are many alternative JVM languages. Some also strongly “Java-compatible” ● Close source and binary mapping to Java – Scala, Groovy, JavaFX, AspectJ ● This holds out the prospect that most Java tools, libraries and frameworks will Just Work, or work with only minor adaptation ● Additional promise of gradual migration of existing Java projects
  • 6. Who's Using It? ● A rapidly growing list of companies and projects, ● Twitter (infrastructure) ● LinkedIn (analytics, infrastructure) ● EDF Trading (analytics, infrastructure) ● Sony Pictures Imageworks (infrastructure) ● SAP/Siemens (ESME, enterprise messaging) ● Novell (Pulse, enterprise messaging)
  • 7. Why Mix OO and FP? ● Each has complementary strengths — ● OO provides excellent support for, – Subtyping and inheritance – Modular components – Classes as partial abstractions ● FP provides excellent support for, – Higher order functions – ADTs, structural recursion and pattern matching – Parametric polymorphism ● They've been converging for a while now
  • 8. Scala has a REPL ● Common in scripting and functional languages ● Great for exploratory programming ● We'll be using it as we go along
  • 9. Scala Cleans Up Java Syntax ● Semi-colons are optional, equals is == ● All statements are expressions and have a value ● Type inference eliminates the most annoying explicit typing annotations ● Case-classes have minimal boilerplate ● Closures and by name arguments allow libraries to define specialized control structures
  • 10. Statically Typed with Inference ● All definitions must have a static type val m : Map[Int, String] ● However these types are typically inferred scala> val m = Map(1 -> "one", 2 -> "two") m : Map[Int, String] = Map(1 -> one, 2 -> two) ● Method return types are also inferred scala> def twice(i : Int) = i*2 twice: (i: Int)Int Argument types must be explicit, also the return types for recursive functions
  • 11. First-Class Functions ● Scala allows the definition of functions def plusOne(x : Int) = x+1 ● Functions can be arguments and results def applyTwice(x : Int, f : Int => Int) = f(f(x)) applyTwice(3, plusOne) // == 5 ● Can be anonymous and close over their environment def twice(f : Int => Int) = (x : Int) => f(f(x)) twice(plusOne)(3) // == 5 ● Function literal syntax is concise twice(_+1)(3) // == 5
  • 12. Higher-Order Functions ● Higher-order functions are used extensively in Scala's standard library List(1, 2, 3).map(_*2) // == List(2, 4, 6) List(1, 2, 3, 4).find(_%2 == 0) // Some(2) List(1, 2, 3, 4).filter(_%2 == 0) // List(2, 4) def recip(x : Int) = if(x == 0) None else Some(1.0/x) scala> List(0, 1, 2, 3).flatMap(recip) res0: List[Int] = List(1.0, 0.5, 0.3333333333333333)
  • 13. For Comprehensions ● Scala's “for comprehensions” capture common patterns of use of map, flatMap and filter val l1 = List(0, 1) val l2 = List(2, 3) scala> for (x <- l1; y <- l2) yield (x, y) res0: List[(Int, Int)] = List((0,2), (0,3), (1,2), (1,3)) The for expression desugars to, l.flatMap(x => l2.map(y => (x, y)) ● These patterns are the monad laws for the subject type
  • 14. Case Classes are Lightweight ● Eliminate a lot of the boilerplate associated with Java implementations of simple data types public class User { private final String name; private final String pass; public User(String name_, String pass_) { name = name_; pass = pass_; } public boolean equals(Object other) { // Stuff ... } public int hashCode() { // More stuff ... } }
  • 15. Case Classes are Lightweight ● The Scala equivalent case class User(name : String, pass : String) ● Accessors, equals, hashCode and toString are provided automatically ● “new” is optional val joe = User("Joe Bloggs", "<secret>") ● “Copy with changes” supports immutable functional objects val joeUpdated = joe.copy(pass = "<still secret>")
  • 16. Pattern Matching ● Case classes model ADTs from functional languages and support pattern matching sealed trait Tree[T] case class Leaf[T](elem : T) extends Tree[T] case class Node[T](left : Tree[T], right : Tree[T]) val t = Node(Node(Leaf("bar"), Leaf("baz")), Leaf("foo")) def find[T](tree : Tree[T], elem : T) : Boolean = tree match { case Node(l, r) => find(l, elem) || find(r, elem) case Leaf(`elem`) => true case _ => false } ● Matching is the inverse of construction
  • 17. The Option Type ● “Null References: The Billion Dollar Mistake” — Tony Hoare ● Scala provides a safe alternative scala> List(1, 2, 3) find (_ == 2) res0: Option[Int] = Some(2) scala> List(1, 2, 3) find (_ == 4) res0: Option[Int] = None ● Option interacts nicely with matching List(1, 2, 3) find (_ == 2) match { case Some(i) => println("Found "+i) case None => println("Not found") }
  • 18. For Comprehensions Again ● Option implements map, flatMap and Filter so works nicely with for comprehensions def goodPair(x : Int, y : Int) = for(fst <- recip(x); snd <- recip(y)) yield (x, y) scala> goodPair(1, 2) res0: Option[(Int, Int)] = Some((1,2)) scala> goodPair(1, 0) res0: Option[(Int, Int)] = None ● Using Option rather than null has clear benefits when used in this way
  • 19. Tools and Frameworks ● Most Java tools and frameworks work with Scala Out Of The Box ● Testing frameworks — ● Specs, ScalaTest, ScalaCheck ● Web frameworks — ● Lift ● Wicket and Play recently added Scala support ● IDE support — the big three (Eclipse, Netbeans, IDEA) all actively developed
  • 20. Roadmap ● Upcoming releases, ● Beta of 2.8 now available ● First 2.8 Release Candidate expected in March ● 2.8 Final expected June/July ● Subsequent 2.8-series releases will continue current exploratory work, ● Type specialization (still needs library support) ● Continuations (currently a compiler plugin) ● Linear/immutable/non-null types
  • 21. Find Out More ● Scala's home at EPFL http://www.scala-lang.org ● See also the scala and scala-user mailing list ● The London Scala Users' Group http://www.meetup.com/london-scala ● Publications ● Programming in Scala Odersky, Venners and Spoon ● Programming in Scala Wampler and Payne
  • 22. An Introduction to Scala Blending OO and Functional Paradigms Miles Sabin, Chuusai Ltd. http://www.chuusai.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin