SlideShare una empresa de Scribd logo
1 de 49
Descargar para leer sin conexión
An 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
●
    Cleaning up Java
●
    Going Beyond Java
●
    Lab 1
●
    Functional Focus
●
    Lab 2
●
    Roadmap
Background
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
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 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 are also strongly “Java-compatible”
    ●
        Close source and binary mapping to Java
        –   Scala, Groovy, JavaFX, AspectJ
●
    For these, prospect is 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
Tools and Frameworks
●
    Idiomatic testing frameworks —
    ●
        Specs, ScalaTest, ScalaCheck
●
    Idiomatic web frameworks —
    ●
        Lift
    ●
        Wicket and Play recently added Scala support
●
    IDE support — the big three (Eclipse,
    Netbeans, IDEA) all actively developed
Who's Using It?
●
    A rapidly growing list of companies and
    projects,
    ●
        Twitter (infrastructure)
    ●
        Foursquare (front-end, infrastructure)
    ●
        LinkedIn (analytics, infrastructure)
    ●
        EDF Trading (analytics, infrastructure)
    ●
        Sony Pictures Imageworks (infrastructure)
    ●
        SAP/Siemens (ESME, enterprise messaging)
    ●
        Novell (Pulse, enterprise messaging)
Meet the REPL
Scala has a REPL
●
    Common in scripting and functional
    languages
●
    Great for exploratory programming
●
    We'll be using it as we go along
Resources

●
    http://www.chuusai.com/spa2010
●
    CDs and Memory Stick circulating
●
    Let me know if you have difficulties
Cleaning up Java
Scala Cleans Up Java Syntax
●
    Semi-colons are optional
●
    equals is ==, == is eq
●
    Periods are optional where unambiguous,
      scala> val s = "Hello world"
      s: java.lang.String = Hello world

      scala> s length
      res8: Int = 11

●
    Binary method invokations can be written
    in operator form,
      scala> s substring 6
      res9: java.lang.String = world
Scala Cleans Up Java Syntax
●
    All statements are expressions and have a
    value,
      val m = if (n % 2 == 0) n/2 else n*3+1

      val pow4 = { val sqr = n*n ; sqr*sqr }

      val n =
        try { s toInt }
        catch { case _ : NumberFormatException => 0 }

●
    Method bodies are expressions and curly
    braces are optional
      def findSlash(s : String) : Int = s indexOf '/'
Statically Typed with Inference
●
    Type inference eliminates the most
    annoying explicit typing annotations
●
    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
Vals, Vars and Uniform Access
●
    Scala simplifies immutable definitions,
      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>")
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 String getName() { return name; }
        public String getPass() { return pass; }
        public boolean equals(Object other) { ... }
        public int hashCode() { ... }
        public String toString() { ... }
      }
Case Classes are Lightweight
●
    The Scala equivalent,
        case class User(name : String, pass : String)

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

    ●
        “Copy with changes” supports immutable
        functional objects
           val joeUpdated = joe.copy(pass = "<still secret>")
No Statics
●
    No static fields or methods
    ●
        Instead "object” entities similar to singletons
        // Java
        public class User {
          public static newUser(String name, String pass) {
            return new User(name, pass);
          }
          // Non-static methods ...
        }

        // Scala
        object User /* extends ((String, String) => User) */{
          def apply(name : String, pass : String) =
            new User(name, pass)
        }
        val joe = User("Joe Bloggs", "<secret>")
Going Beyond
    Java
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,
      x + 1 // equivalent to x.+(1)

●
    Classes can define methods which can
    invoked in operator form,
      case class Complex(val re : Double, val im : Double) {
        def +(rhs : Complex) = Complex(re+rhs.re, im+rhs.im)
        def *(rhs : Complex) =
          Complex(re*rhs.re-im*rhs.im, im*rhs.re+re*rhs.im)
      }
      val c1 = Complex(1.0, 1.0) ; val c2 = Complex(2.0, 3.0)
      c1+c2 // == Complex(3.0, 4.0)
      c1*c2 // == Complex(-1.0, 5.0)
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, ", ")
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 ...")
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](l: Tree[T], r: Tree[T]) extends Tree[T]

      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
        }

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

●
    Matching is the inverse of construction
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(msg : String) {
          println("Sending: "+msg) // 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

●
    Create circular structures without update,
      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 }
Implicit Conversions
●
    Implicit functions provide a way to attach
    new behaviours to exisiting types
●
    Invoked if needed to typecheck
      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 }

●
    Provides Haskell-like ad hoc polymorphism
The Scala IDE for
     Eclipse
Main Features
●
    Extends the JDT to support mixed
    Scala/Java projects
●
    Semantically aware editor
●
    Project and source navigation
●
    Incremental builder
●
    Integrated debugger
●
    Free, open source ...
Participate!
●
    The Scala IDE for Eclipse's home
    http://www.scala-ide.org/
●
    Wiki, git repository, bugs
    http://scala-ide.assembla.com/
●
    Mailing lists
    http://groups.google.com/group/scala-ide-user
    http://groups.google.com/group/scala-ide-dev
●
    Follow @ScalaIDE on Twitter
Resources

●
    http://www.chuusai.com/spa2010
●
    CDs and Memory Stick circulating
●
    Let me know if you have difficulties
Lab 1
Functional Focus
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)
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
●
    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
Resources

●
    http://www.chuusai.com/spa2010
●
    CDs and Memory Stick circulating
●
    Let me know if you have difficulties
Lab 2
Roadmap
Roadmap
●
    Upcoming releases,
    ●
        Release Candidate 2 of 2.8 now available
    ●
        2.8 Final expected July/August
●
    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
            for Java Developers




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

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

Más contenido relacionado

La actualidad más candente

Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
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
 

La actualidad más candente (17)

Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala
ScalaScala
Scala
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
All about scala
All about scalaAll about scala
All about scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
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
 

Destacado

Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Kicking Butt on Concurrent Enterprise Application with Scala
Kicking Butt on Concurrent Enterprise Application with ScalaKicking Butt on Concurrent Enterprise Application with Scala
Kicking Butt on Concurrent Enterprise Application with ScalaLinuxmalaysia Malaysia
 
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
 

Destacado (6)

2.3 implicits
2.3 implicits2.3 implicits
2.3 implicits
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Kicking Butt on Concurrent Enterprise Application with Scala
Kicking Butt on Concurrent Enterprise Application with ScalaKicking Butt on Concurrent Enterprise Application with Scala
Kicking Butt on Concurrent Enterprise Application with Scala
 
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
 
2.6 summary day-2
2.6 summary day-22.6 summary day-2
2.6 summary day-2
 
2.5 the quiz-game
2.5 the quiz-game2.5 the quiz-game
2.5 the quiz-game
 

Similar a 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 DevelopersMiles Sabin
 
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
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresqueBret McGuire
 
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
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
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
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistpmanvi
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
(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
 

Similar a An Introduction to Scala for Java Developers (20)

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
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
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
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
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 for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
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?
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With 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 and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
(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?
 

Más 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
 

Más 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
 

Último

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Último (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
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
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

An Introduction to Scala for Java Developers

  • 1. An 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 ● Cleaning up Java ● Going Beyond Java ● Lab 1 ● Functional Focus ● Lab 2 ● Roadmap
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. Interoperbility with Java ● There are many alternative JVM languages. Some are also strongly “Java-compatible” ● Close source and binary mapping to Java – Scala, Groovy, JavaFX, AspectJ ● For these, prospect is 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
  • 8. Tools and Frameworks ● Idiomatic testing frameworks — ● Specs, ScalaTest, ScalaCheck ● Idiomatic web frameworks — ● Lift ● Wicket and Play recently added Scala support ● IDE support — the big three (Eclipse, Netbeans, IDEA) all actively developed
  • 9. Who's Using It? ● A rapidly growing list of companies and projects, ● Twitter (infrastructure) ● Foursquare (front-end, infrastructure) ● LinkedIn (analytics, infrastructure) ● EDF Trading (analytics, infrastructure) ● Sony Pictures Imageworks (infrastructure) ● SAP/Siemens (ESME, enterprise messaging) ● Novell (Pulse, enterprise messaging)
  • 11. Scala has a REPL ● Common in scripting and functional languages ● Great for exploratory programming ● We'll be using it as we go along
  • 12. Resources ● http://www.chuusai.com/spa2010 ● CDs and Memory Stick circulating ● Let me know if you have difficulties
  • 14. Scala Cleans Up Java Syntax ● Semi-colons are optional ● equals is ==, == is eq ● Periods are optional where unambiguous, scala> val s = "Hello world" s: java.lang.String = Hello world scala> s length res8: Int = 11 ● Binary method invokations can be written in operator form, scala> s substring 6 res9: java.lang.String = world
  • 15. Scala Cleans Up Java Syntax ● All statements are expressions and have a value, val m = if (n % 2 == 0) n/2 else n*3+1 val pow4 = { val sqr = n*n ; sqr*sqr } val n = try { s toInt } catch { case _ : NumberFormatException => 0 } ● Method bodies are expressions and curly braces are optional def findSlash(s : String) : Int = s indexOf '/'
  • 16. Statically Typed with Inference ● Type inference eliminates the most annoying explicit typing annotations ● 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
  • 17. Vals, Vars and Uniform Access ● Scala simplifies immutable definitions, 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>")
  • 18. 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 String getName() { return name; } public String getPass() { return pass; } public boolean equals(Object other) { ... } public int hashCode() { ... } public String toString() { ... } }
  • 19. Case Classes are Lightweight ● The Scala equivalent, case class User(name : String, pass : String) ● Accessors, toString and correct equals and hashCode provided automatically ● “new” omitted val joe = User("Joe Bloggs", "<secret>") ● “Copy with changes” supports immutable functional objects val joeUpdated = joe.copy(pass = "<still secret>")
  • 20. No Statics ● No static fields or methods ● Instead "object” entities similar to singletons // Java public class User { public static newUser(String name, String pass) { return new User(name, pass); } // Non-static methods ... } // Scala object User /* extends ((String, String) => User) */{ def apply(name : String, pass : String) = new User(name, pass) } val joe = User("Joe Bloggs", "<secret>")
  • 21. Going Beyond Java
  • 22. Scala is Object Oriented ● Scala has a uniform object model: no primitive types
  • 23. Scala is Object Oriented ● Operators aren't special, they're methods like any other, x + 1 // equivalent to x.+(1) ● Classes can define methods which can invoked in operator form, case class Complex(val re : Double, val im : Double) { def +(rhs : Complex) = Complex(re+rhs.re, im+rhs.im) def *(rhs : Complex) = Complex(re*rhs.re-im*rhs.im, im*rhs.re+re*rhs.im) } val c1 = Complex(1.0, 1.0) ; val c2 = Complex(2.0, 3.0) c1+c2 // == Complex(3.0, 4.0) c1*c2 // == Complex(-1.0, 5.0)
  • 24. 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, ", ")
  • 25. 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 ...")
  • 26. 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](l: Tree[T], r: Tree[T]) extends Tree[T] 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 } val t = Node(Node(Leaf("bar"), Leaf("baz")), Leaf("foo")) find(t, "baz") // true ● Matching is the inverse of construction
  • 27. 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)
  • 28. Mixin Composition ● Traits support multiple inheritance whilst avoiding the problems of “diamond” inheritance trait Email { val address : String def send(msg : String) { println("Sending: "+msg) // 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!")
  • 29. 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 ● Create circular structures without update, abstract class Link { val next : Link } val (a : Link, b : Link) = (new Link { lazy val next = b }, new Link { lazy val next = a })
  • 30. 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 */ }
  • 31. 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 }
  • 32. Implicit Conversions ● Implicit functions provide a way to attach new behaviours to exisiting types ● Invoked if needed to typecheck 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 } ● Provides Haskell-like ad hoc polymorphism
  • 33. The Scala IDE for Eclipse
  • 34. Main Features ● Extends the JDT to support mixed Scala/Java projects ● Semantically aware editor ● Project and source navigation ● Incremental builder ● Integrated debugger ● Free, open source ...
  • 35. Participate! ● The Scala IDE for Eclipse's home http://www.scala-ide.org/ ● Wiki, git repository, bugs http://scala-ide.assembla.com/ ● Mailing lists http://groups.google.com/group/scala-ide-user http://groups.google.com/group/scala-ide-dev ● Follow @ScalaIDE on Twitter
  • 36. Resources ● http://www.chuusai.com/spa2010 ● CDs and Memory Stick circulating ● Let me know if you have difficulties
  • 37. Lab 1
  • 39. 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
  • 40. 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)
  • 41. 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") }
  • 42. 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
  • 43. 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
  • 44. Resources ● http://www.chuusai.com/spa2010 ● CDs and Memory Stick circulating ● Let me know if you have difficulties
  • 45. Lab 2
  • 47. Roadmap ● Upcoming releases, ● Release Candidate 2 of 2.8 now available ● 2.8 Final expected July/August ● 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
  • 48. 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
  • 49. An Introduction to Scala for Java Developers Miles Sabin, Chuusai Ltd. http://www.chuusai.com/ http://uk.linkedin.com/in/milessabin http://twitter.com/milessabin