SlideShare a Scribd company logo
1 of 36
A Brief Introduction to Scala
         for Java Developers




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

       http://uk.linkedin.com/in/milessabin
              http://twitter.com/milessabin
Outline
●
    Background
●
    Object-Oriented Features
●
    Functional 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
Scala is Object Oriented
●
    Scala has a uniform object model: no
    primitive types
Scala is Object Oriented
●
    Operators aren't special, they're methods
    like any other,
      val x = 23
      x + 1 // equivalent to x.+(1)

●
    Similarly, methods can be invoked in
    operator form,
      val s = "Hello world"
      s length              // equivalent to s.length
      s contains "world"    // equivalent to s.contains("world")
No Statics
●
    No static fields or methods
●
    Instead we have first-class "object” entities
    similar to singletons and ML modules
      // Java
      public class User {
        public static newUser(String name, String pass) {
          return new User(name, pass);
        }
        // Non-static methods ...
      }
      // Scala
      object User {
        def apply(name : String, pass : String) =
          new User(name, pass)
      }
      val joe = User("Joe Bloggs", "<secret>")
Vals, Vars and Uniform Access
●
    Scala makes immutable definitions easy,
      val   s : String =   "Hello immutable world"
      s =   "Bye ..." //   Error
      var   t : String =   "Hello mutable world"
      t =   "Bye ..." //   OK

●
    (Im)mutable properties can be
    implemented by vals, vars or methods
      class   User {
        val   name : String        // Immutable
        var   email : String       // Mutable
        def   pass : String        // Computed
        def   pass_=(s : String)   //
      }

      user.pass = "<secret>" // Sugar for user.pass_=("<secret>")
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
Named and Default Arguments
●
    Arguments can be specified at call sites by
    name
      def coord(x : Double, y : Double)
      coord(y = 1.0, x = 0.7)

    Allows them to be provided naturally for
    the call site, and eliminates ambiguity
●
    Arguments can also be given default values
      def printList(l : List[Int], sep : String =", ") { ... }

      val l = List(1, 2, 3)
      printList(l) // equivalent to printList(l, ", ")
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")
      }
Tuples
●
    Scala has tuple types and literals
      val coord : (Double, Double) = (1.0, 0.5)
      println("x = "+coord._1+", y ="+coord._2)

●
    These are first-class types like any other
      val coords = new ListBuffer[(Double, Double)]
      coords += coord

●
    Provide ad hoc grouping and multiple
    return values
      def firstWord(s : String) = {
        val i = s+" " indexOf ' '
        (s.substring(0, i), s.substring(i, s.length))
      }
      val (first, rest) = firstWord("The quick brown fox ...")
Mixin Composition
●
    Java interfaces are replaced by traits and
    mixin composition
    ●
        Traits can provide method implementations
    ●
        Traits can provide fields
        trait   UserId {
          val   name : String
          var   pass : String = "change me"
          def   display = name+":"+pass
        }
        class   User(val name : String) extends UserId

        val joe = new User("Joe Bloggs")
        println(joe.display)
Mixin Composition
●
    Traits support multiple inheritance whilst
    avoiding the problems of “diamond”
    inheritance
      trait Email {
        val address : String
        def send(message : String {
          // Concrete implementation
        }
      }
      class User(val name : String, val address : String)
        extends UserId with Email

      val joe = new User("Joe Bloggs", "joe@gmail.com")
      println(joe.display)
      joe.send("Don't forget to change your password!")
Laziness and By-Name Args
●
    Values can be declared to be initialized
    lazily
      val (title, givenName, surname) = ("Mr.", "John", "Smith")
      lazy val fullName = title+" "+givenName+" "+surname

    The value is computed the first time it is
    used (if at all)
      val displayName = if (full) fullName else givenName

●
    Can be used to create circular structures
      abstract class   Link { val next : Link }
      val (a : Link,   b : Link) =
         (new Link {   lazy val next = b },
          new Link {   lazy val next = a })
Laziness and By-Name Args
●
    Arguments can be passed by name
    ●
        Similar to laziness in that evaluation is deferred
        until use
    ●
        Can be used to build specialized control
        structures and enables internal DSLs
          def locked[T](l : Lock)(op : => T) = {
            l.lock
            try { op } finally { l.unlock }
          }
          val lock = new ReentrantLock
          var shared = ...
          locked(lock) {
            /* Use shared while holding lock */
          }
Structural Typing
●
    Scala has a form of statically checkable
    duck-typing
●
    We can use this to generalize libraries to
    pre-existing types
      type Closeable = { def close() }

      def using[R <: Closeable, T](res : R)(op : R => T) =
        try { op(res) } finally { res.close() }

      val b = using(new FileInputStream("test.txt")) { _.read }
Implicits
●
    Implicit functions provide a way to attach
    new behaviours to exisiting types
●
    Invoked automatically if needed to satisfy
    the typechecker
      trait Closeable { def close : Unit }

      def using[R <% Closeable, T](res : R)(op : R => T) =
        try { op(res) } finally { res.close() }

      implicit def InputStreamIsCloseable(is : InputStream) =
        new Closeable { def close = in.close }

      val b = using(new FileInputStream("test.txt")) { _.read }
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
For Comprehensions
●
    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
Language-Level XML Support
●
    Scala has language level support for XML
    via XML literals, XPath and pattern
    matching,
    val book =
      <book>
        <author>Martin Odersky</author>
        <title>Programming in Scala</title>
      </book>

    val title = book  “title” text // == “Programming in ... “

    for (elem <- book.child) elem match {
      case <author>{name}</author> => println(name)
      case _ =>
    } // Prints “Martin Odersky”
Actor-based Concurrency
●
    Scala has library level support for actor-
    based, message-passing concurrency
    ●
        An embarrassment of riches —
        –   scala.actors
        –   Lift actors
        –   Akka
●
    Not obligatory, these are all libraries, and
    all the traditional Java approaches to
    concurrency are available
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
A Brief Introduction to Scala
         for Java Developers




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

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

More Related Content

What's hot

Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaBasuk
 
Unraveling the mystery of monads
Unraveling the mystery of monadsUnraveling the mystery of monads
Unraveling the mystery of monadsFaisal Waris
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsMiles Sabin
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresqueBret McGuire
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingMeir Maor
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless Jared Roesch
 

What's hot (18)

Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Unraveling the mystery of monads
Unraveling the mystery of monadsUnraveling the mystery of monads
Unraveling the mystery of monads
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Java
Java Java
Java
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Demystifying Shapeless
Demystifying Shapeless Demystifying Shapeless
Demystifying Shapeless
 

Viewers also liked

Lessons Learned From Uber Prof
Lessons Learned From Uber ProfLessons Learned From Uber Prof
Lessons Learned From Uber ProfSkills Matter
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog SampleSkills Matter
 
Geek Nights Neo4j Code Jam
Geek Nights Neo4j Code JamGeek Nights Neo4j Code Jam
Geek Nights Neo4j Code JamSkills Matter
 
5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard LawrenceSkills Matter
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 

Viewers also liked (6)

Lessons Learned From Uber Prof
Lessons Learned From Uber ProfLessons Learned From Uber Prof
Lessons Learned From Uber Prof
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Geek Nights Neo4j Code Jam
Geek Nights Neo4j Code JamGeek Nights Neo4j Code Jam
Geek Nights Neo4j Code Jam
 
5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 

Similar to Miles Sabin Introduction To Scala For Java Developers

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
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
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
 
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
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 

Similar to Miles Sabin Introduction To Scala For Java Developers (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
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
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
 
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
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
scala-101
scala-101scala-101
scala-101
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 

More from Skills Matter

Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmSkills Matter
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimSkills Matter
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Skills Matter
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlSkills Matter
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsSkills Matter
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Skills Matter
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Skills Matter
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldSkills Matter
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Skills Matter
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Skills Matter
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingSkills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveSkills Matter
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tSkills Matter
 
Bootstrapping a-devops-matter
Bootstrapping a-devops-matterBootstrapping a-devops-matter
Bootstrapping a-devops-matterSkills Matter
 

More from Skills Matter (20)

Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberl
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.js
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source world
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testing
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
 
Serendipity-neo4j
Serendipity-neo4jSerendipity-neo4j
Serendipity-neo4j
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Plug 20110217
Plug   20110217Plug   20110217
Plug 20110217
 
Lug presentation
Lug presentationLug presentation
Lug presentation
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
 
Plug saiku
Plug   saikuPlug   saiku
Plug saiku
 
Huguk lily
Huguk lilyHuguk lily
Huguk lily
 
Bootstrapping a-devops-matter
Bootstrapping a-devops-matterBootstrapping a-devops-matter
Bootstrapping a-devops-matter
 

Recently uploaded

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 

Recently uploaded (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 

Miles Sabin Introduction To Scala For Java Developers

  • 1. A Brief Introduction to Scala for Java Developers Miles Sabin, Chuusai Ltd. http://www.chuusai.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin
  • 2. Outline ● Background ● Object-Oriented Features ● Functional 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. Scala is Object Oriented ● Scala has a uniform object model: no primitive types
  • 11. Scala is Object Oriented ● Operators aren't special, they're methods like any other, val x = 23 x + 1 // equivalent to x.+(1) ● Similarly, methods can be invoked in operator form, val s = "Hello world" s length // equivalent to s.length s contains "world" // equivalent to s.contains("world")
  • 12. No Statics ● No static fields or methods ● Instead we have first-class "object” entities similar to singletons and ML modules // Java public class User { public static newUser(String name, String pass) { return new User(name, pass); } // Non-static methods ... } // Scala object User { def apply(name : String, pass : String) = new User(name, pass) } val joe = User("Joe Bloggs", "<secret>")
  • 13. Vals, Vars and Uniform Access ● Scala makes immutable definitions easy, val s : String = "Hello immutable world" s = "Bye ..." // Error var t : String = "Hello mutable world" t = "Bye ..." // OK ● (Im)mutable properties can be implemented by vals, vars or methods class User { val name : String // Immutable var email : String // Mutable def pass : String // Computed def pass_=(s : String) // } user.pass = "<secret>" // Sugar for user.pass_=("<secret>")
  • 14. 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
  • 15. Named and Default Arguments ● Arguments can be specified at call sites by name def coord(x : Double, y : Double) coord(y = 1.0, x = 0.7) Allows them to be provided naturally for the call site, and eliminates ambiguity ● Arguments can also be given default values def printList(l : List[Int], sep : String =", ") { ... } val l = List(1, 2, 3) printList(l) // equivalent to printList(l, ", ")
  • 16. 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 ... } }
  • 17. 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>")
  • 18. 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
  • 19. 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") }
  • 20. Tuples ● Scala has tuple types and literals val coord : (Double, Double) = (1.0, 0.5) println("x = "+coord._1+", y ="+coord._2) ● These are first-class types like any other val coords = new ListBuffer[(Double, Double)] coords += coord ● Provide ad hoc grouping and multiple return values def firstWord(s : String) = { val i = s+" " indexOf ' ' (s.substring(0, i), s.substring(i, s.length)) } val (first, rest) = firstWord("The quick brown fox ...")
  • 21. Mixin Composition ● Java interfaces are replaced by traits and mixin composition ● Traits can provide method implementations ● Traits can provide fields trait UserId { val name : String var pass : String = "change me" def display = name+":"+pass } class User(val name : String) extends UserId val joe = new User("Joe Bloggs") println(joe.display)
  • 22. Mixin Composition ● Traits support multiple inheritance whilst avoiding the problems of “diamond” inheritance trait Email { val address : String def send(message : String { // Concrete implementation } } class User(val name : String, val address : String) extends UserId with Email val joe = new User("Joe Bloggs", "joe@gmail.com") println(joe.display) joe.send("Don't forget to change your password!")
  • 23. Laziness and By-Name Args ● Values can be declared to be initialized lazily val (title, givenName, surname) = ("Mr.", "John", "Smith") lazy val fullName = title+" "+givenName+" "+surname The value is computed the first time it is used (if at all) val displayName = if (full) fullName else givenName ● Can be used to create circular structures abstract class Link { val next : Link } val (a : Link, b : Link) = (new Link { lazy val next = b }, new Link { lazy val next = a })
  • 24. Laziness and By-Name Args ● Arguments can be passed by name ● Similar to laziness in that evaluation is deferred until use ● Can be used to build specialized control structures and enables internal DSLs def locked[T](l : Lock)(op : => T) = { l.lock try { op } finally { l.unlock } } val lock = new ReentrantLock var shared = ... locked(lock) { /* Use shared while holding lock */ }
  • 25. Structural Typing ● Scala has a form of statically checkable duck-typing ● We can use this to generalize libraries to pre-existing types type Closeable = { def close() } def using[R <: Closeable, T](res : R)(op : R => T) = try { op(res) } finally { res.close() } val b = using(new FileInputStream("test.txt")) { _.read }
  • 26. Implicits ● Implicit functions provide a way to attach new behaviours to exisiting types ● Invoked automatically if needed to satisfy the typechecker trait Closeable { def close : Unit } def using[R <% Closeable, T](res : R)(op : R => T) = try { op(res) } finally { res.close() } implicit def InputStreamIsCloseable(is : InputStream) = new Closeable { def close = in.close } val b = using(new FileInputStream("test.txt")) { _.read }
  • 27. 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
  • 28. 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)
  • 29. 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
  • 30. For Comprehensions ● 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
  • 31. Language-Level XML Support ● Scala has language level support for XML via XML literals, XPath and pattern matching, val book = <book> <author>Martin Odersky</author> <title>Programming in Scala</title> </book> val title = book “title” text // == “Programming in ... “ for (elem <- book.child) elem match { case <author>{name}</author> => println(name) case _ => } // Prints “Martin Odersky”
  • 32. Actor-based Concurrency ● Scala has library level support for actor- based, message-passing concurrency ● An embarrassment of riches — – scala.actors – Lift actors – Akka ● Not obligatory, these are all libraries, and all the traditional Java approaches to concurrency are available
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. A Brief Introduction to Scala for Java Developers Miles Sabin, Chuusai Ltd. http://www.chuusai.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin