SlideShare a Scribd company logo
1 of 34
Download to read offline
e
       Scala
Programming Language

    Christopher League
        LIU Brooklyn



        February 
Prehistory
 Martin Odersky receives Ph.D. from
     Niklaus Wirth at ETH Zürich.
 Odersky and Phil Wadler team up to design
     Pizza, a functional language that targets
     Java Virtual Machine.
 Propose Generic Java, with Gilad Bracha
     and David Stoutamire
History
   Sun proposes to incorporate Generic Java
   Odersky begins design of Scala at EPFL
   GJ compiler released as Java .
   First public Scala release
   Scala version  release
   Typesafe Inc. founded to support and
       promote Scala.
Who uses Scala?
AppJet            Office Depot
Ebay              SAIC
Foursquare        Siemens
GridGain          Sony
Guardian          Sygneca
LinkedIn          atcham
Managed Gaming    Twitter
Nature            WattzOn
Novell            Xebia
Novus Partners    Xerox
OPower            ...
Who uses Scala?
One-slide summary: Scala is...
Scalable
Object-oriented
Functional
Compatible
Concise
High-level
Statically typed
Interactive (REPL)
Scala is... concise
Typical Java class definition
class MyClass {
    private int index;
    private String name;
    public MyClass(int index, String name) {
        this.index = index;
        this.name = name;
    }
}

Equivalent Scala class definition
class MyClass(index: Int, name: String)
Scala is... high-level
Java: Does a string have an uppercase character?
boolean nameHasUpperCase = false;
for (int i = 0; i < name.length(); ++i) {
    if (Character.isUpperCase(name.charAt(i))) {
        nameHasUpperCase = true;
        break;
    }
}

Equivalent Scala:
val nameHasUpperCase = name.exists(_.isUpper)
Acknowledgment
Agenda
. Introduction to Scala
. Object-oriented programming
   . Objects, classes, and traits
   . Collections hierarchy
. Functional programming
   . Immutability
   . Higher-order functions
   . Algebraic data types
. Concurrency
. Summary and resources
Objects and classes
In Java and C++, classes...
   . are a template for creating new objects dynamically
   . define the methods and fields of those objects
   . provide a namespace for static methods and
      fields, unconnected to a particular object
In Scala,
      Classes are responsible only for  and .
      For , we define a singleton object as a container
      for static members.
Example
class ChecksumAccumulator {
    private var sum = 0
    def add(b: Byte) { sum += b }
    def checksum(): Int = ˜(sum & 0xFF) + 1
}
object ChecksumAccumulator {
    private val cache = Map[String, Int]()
    def calculate(s: String): Int =
      if (cache.contains(s)) cache(s)
      else {
        val acc = new ChecksumAccumulator
        for (c <- s) acc.add(c.toByte)
        val cs = acc.checksum()
        cache += (s -> cs)
        cs
      }
Other notable features
Identifiers declared as either val (immutable value)
or var (mutable variable)
Methods introduced by def
Array/map/function syntax are unified: cache(s)
Instantiation of generic types: Map[String, Int]
if/else returns a value
Last expression of a block is returned, as long as
method body preceded by ‘=’
Very general loop syntax: for(x <- xs) . . .
                                (More on that later...)
Immutable object example
class Rational(n: Int, d: Int) { // main constructor
    require(d != 0) // or else IllegalArgumentException
    private val g = gcd(n.abs, d.abs)
    val numer = n / g
    val denom = d / g
    def this(n: Int) = this(n, 1) // auxiliary c’tor
    def add(that: Rational): Rational =
        new Rational
          (numer * that.denom + that.numer * denom,
           denom * that.denom)
    override def toString = numer + ”/” + denom
    private def gcd(a: Int, b: Int): Int =
        if (b == 0) a else gcd(b, a % b)
}
Traits
A trait encapsulates method and field definitions,
which can then be reused by mixing them into
classes.
A class can mix in any number of traits, defining
stackable modifications.
Traits example
class Animal(val name: String) {
  override def toString = name
}
trait Philosophical {
  def think {
    println(this + ”: ” +
      ”I consume memory, therefore I am.”)
  }
}
class Squid extends Animal(”Søren”) with Philosophical
trait HasLegs {
  def legCount: Int
  def jump {
    println(this + ”: How high?”)
  }
}
Traits example
class Frog(name: String) extends Animal(name)
with HasLegs with Philosophical {
  override def think {
    println(this + ”: It ain’t easy being green.”)
  }
  def legCount = 4
}
trait Biped extends HasLegs {
  def legCount = 2
}
class Human(name: String) extends Animal(name)
with Biped with Philosophical
Traits example
scala> val s = new Squid
s: Squid = Søren
scala> val f = new Frog(”Kermit”)
f: Frog = Kermit
scala> val h = new Human(”Alice”)
h: Human = Alice
scala> s.think
Søren: I consume memory, therefore I am.
scala> f.think
Kermit: It aint easy being green.
scala> h.legCount
res3: Int = 2
scala> f.legCount
res4: Int = 4
scala> s.legCount
error: value legCount is not a member of Squid
Collections hierarchy
Live-coding in REPL with collections
Agenda
. Introduction to Scala
. Object-oriented programming
   . Objects, classes, and traits
   . Collections hierarchy
. Functional programming
   . Immutability
   . Higher-order functions
   . Algebraic data types
. Concurrency
. Summary and resources
Immutability
    Identifiers declared as either val (immutable value)
    or var (mutable variable)
    scala.collection.immutable vs.
    scala.collection.mutable
scala> import scala.collection.mutable.{Set => MSet}
scala> import scala.collection.immutable.Set
scala> val s1 = MSet(2,6,7,9)
scala> val s2 = Set(3,4,7,8)
scala> s1 += 5
res9: s1.type = Set(9, 2, 6, 7, 5)
scala> s1 contains 5
res10: Boolean = true
scala> s2 += 5
error: reassignment to val
Why prefer immutability?
Referential transparency — easier for compilers
and people to reason about code if f(x) always
equals f(x)
Concurrency — multiple threads updating a single
variable or data structure can corrupt it. Fewer
updates make it easier to prevent corruption.
Higher-order functions
Function values can be passed to other functions,
stored in data structures. Syntax of function value:
{ (x: Int) => x * x }
{ x => x * 2 } // if type can be inferred
{ _ * 2 } // if parameter used just once

Example from before: name.exists( .isUpper)
Define your own control structures!
def unless(cond: Boolean)(block: =>Unit) =
    if(!cond) block

unless(3 < 1) { println(”Huh.”) }
e flexible ‘for’ comprehension
scala> for(i <- 0 to 3; j <- i+1 to 4) yield (i,j)
scala.collection.immutable.IndexedSeq[(Int, Int)] =
Vector((0,1), (0,2), (0,3), (0,4),
             (1,2), (1,3), (1,4),
                   (2,3), (2,4),
                          (3,4))

‘for’ is based entirely on higher-order functions:
    (0 to 3).flatMap(i =>
        (i+1 to 4).map(j =>
            (i,j)))
// where:
    flatMap[B](A => TraversableOnce[B]): Seq[B]
    map[B](A => B): Seq[B]
Algebraic data types
Based on case classes in Scala:
  abstract class Tree[A]
  case class Leaf[A](value: A) extends Tree[A]
  case class Branch[A](
      left: Tree[A], right: Tree[A]
  ) extends Tree[A]

You can construct objects without new
All parameters become immutable fields
Compiler generates sensible toString, equals,
and copy methods.
Live-coding binary tree operations
Agenda
. Introduction to Scala
. Object-oriented programming
   . Objects, classes, and traits
   . Collections hierarchy
. Functional programming
   . Immutability
   . Higher-order functions
   . Algebraic data types
. Concurrency
. Summary and resources
Scala actor asynchronicity
scala> import scala.actors.Actor._

scala> actor{println(”TICK”)}; println(”TOCK”)
TOCK
TICK

scala> actor{println(”TICK”)}; println(”TOCK”)
TICK
TOCK
Concurrency is hard
Scala actors
Actors are objects that send/receive messages.
a ! m sends message m to actor a, and returns
immediately (fire and forget).
System serializes message receives within actor.
react does not block thread, but also does not
return.
Can arrange computations to follow react using
loop, andThen.
Scala actor messaging
import scala.actors.Actor._
case object Incr
case object Get
val counter = actor {
  var n = 0
  loop {    // repeatedly wait for a message
    react { // (but don’t block thread)
      case Incr => n += 1; println(n)
      case Get => sender ! n
    }
  }
}
counter ! Incr // fire and forget; eventually
counter ! Incr // prints ’1’ then ’2’
Future power people
scala> counter ! Incr
scala> counter ! Incr
3
4
scala> val f = counter !! Get
f: z.Future[Any] = <function0>
scala> f.foreach { case x: Int =>
          println(”Square is ” + x*x) }
Square is 16
‘For’ the future
Because Future implements standard collection
methods like flatMap, you can sequence
asynchronous computations with ‘for’ syntax:
for(r1 <- act1 !! SomeOperation(x1,x2);
    r2 <- act2 !! AnotherOperation(r1,y1,y2))
{
    storeResult(r2)
}
Resources




scala-lang.org      typesafe.com      Free* e-book:




slidesha.re/BnNJu ny-scala meetup

More Related Content

What's hot

Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 
Oscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleOscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleMartin Odersky
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellDatabricks
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako, Vasil Remeniuk
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 

What's hot (18)

Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
Oscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simpleOscon keynote: Working hard to keep it simple
Oscon keynote: Working hard to keep it simple
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van HovellAn Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
An Introduction to Higher Order Functions in Spark SQL with Herman van Hovell
 
Google06
Google06Google06
Google06
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 

Viewers also liked

Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
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 Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

Viewers also liked (7)

Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
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 Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similar to The Scala Programming Language

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
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
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 - 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
 

Similar to The Scala Programming Language (20)

Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
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?
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
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 ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
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?
 

More from league

On the Edge, 2013
On the Edge, 2013On the Edge, 2013
On the Edge, 2013league
 
On the edge
On the edgeOn the edge
On the edgeleague
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systemsleague
 
Programming Android
Programming AndroidProgramming Android
Programming Androidleague
 
Futzing with actors (etc.)
Futzing with actors (etc.)Futzing with actors (etc.)
Futzing with actors (etc.)league
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
Monadologie
MonadologieMonadologie
Monadologieleague
 

More from league (7)

On the Edge, 2013
On the Edge, 2013On the Edge, 2013
On the Edge, 2013
 
On the edge
On the edgeOn the edge
On the edge
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
 
Programming Android
Programming AndroidProgramming Android
Programming Android
 
Futzing with actors (etc.)
Futzing with actors (etc.)Futzing with actors (etc.)
Futzing with actors (etc.)
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Monadologie
MonadologieMonadologie
Monadologie
 

The Scala Programming Language

  • 1. e Scala Programming Language Christopher League LIU Brooklyn  February 
  • 2. Prehistory  Martin Odersky receives Ph.D. from Niklaus Wirth at ETH Zürich.  Odersky and Phil Wadler team up to design Pizza, a functional language that targets Java Virtual Machine.  Propose Generic Java, with Gilad Bracha and David Stoutamire
  • 3. History  Sun proposes to incorporate Generic Java  Odersky begins design of Scala at EPFL  GJ compiler released as Java .  First public Scala release  Scala version  release  Typesafe Inc. founded to support and promote Scala.
  • 4. Who uses Scala? AppJet Office Depot Ebay SAIC Foursquare Siemens GridGain Sony Guardian Sygneca LinkedIn atcham Managed Gaming Twitter Nature WattzOn Novell Xebia Novus Partners Xerox OPower ...
  • 6. One-slide summary: Scala is... Scalable Object-oriented Functional Compatible Concise High-level Statically typed Interactive (REPL)
  • 7. Scala is... concise Typical Java class definition class MyClass { private int index; private String name; public MyClass(int index, String name) { this.index = index; this.name = name; } } Equivalent Scala class definition class MyClass(index: Int, name: String)
  • 8. Scala is... high-level Java: Does a string have an uppercase character? boolean nameHasUpperCase = false; for (int i = 0; i < name.length(); ++i) { if (Character.isUpperCase(name.charAt(i))) { nameHasUpperCase = true; break; } } Equivalent Scala: val nameHasUpperCase = name.exists(_.isUpper)
  • 10. Agenda . Introduction to Scala . Object-oriented programming . Objects, classes, and traits . Collections hierarchy . Functional programming . Immutability . Higher-order functions . Algebraic data types . Concurrency . Summary and resources
  • 11. Objects and classes In Java and C++, classes... . are a template for creating new objects dynamically . define the methods and fields of those objects . provide a namespace for static methods and fields, unconnected to a particular object In Scala, Classes are responsible only for  and . For , we define a singleton object as a container for static members.
  • 12. Example class ChecksumAccumulator { private var sum = 0 def add(b: Byte) { sum += b } def checksum(): Int = ˜(sum & 0xFF) + 1 } object ChecksumAccumulator { private val cache = Map[String, Int]() def calculate(s: String): Int = if (cache.contains(s)) cache(s) else { val acc = new ChecksumAccumulator for (c <- s) acc.add(c.toByte) val cs = acc.checksum() cache += (s -> cs) cs }
  • 13. Other notable features Identifiers declared as either val (immutable value) or var (mutable variable) Methods introduced by def Array/map/function syntax are unified: cache(s) Instantiation of generic types: Map[String, Int] if/else returns a value Last expression of a block is returned, as long as method body preceded by ‘=’ Very general loop syntax: for(x <- xs) . . . (More on that later...)
  • 14. Immutable object example class Rational(n: Int, d: Int) { // main constructor require(d != 0) // or else IllegalArgumentException private val g = gcd(n.abs, d.abs) val numer = n / g val denom = d / g def this(n: Int) = this(n, 1) // auxiliary c’tor def add(that: Rational): Rational = new Rational (numer * that.denom + that.numer * denom, denom * that.denom) override def toString = numer + ”/” + denom private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) }
  • 15. Traits A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. A class can mix in any number of traits, defining stackable modifications.
  • 16. Traits example class Animal(val name: String) { override def toString = name } trait Philosophical { def think { println(this + ”: ” + ”I consume memory, therefore I am.”) } } class Squid extends Animal(”Søren”) with Philosophical trait HasLegs { def legCount: Int def jump { println(this + ”: How high?”) } }
  • 17. Traits example class Frog(name: String) extends Animal(name) with HasLegs with Philosophical { override def think { println(this + ”: It ain’t easy being green.”) } def legCount = 4 } trait Biped extends HasLegs { def legCount = 2 } class Human(name: String) extends Animal(name) with Biped with Philosophical
  • 18. Traits example scala> val s = new Squid s: Squid = Søren scala> val f = new Frog(”Kermit”) f: Frog = Kermit scala> val h = new Human(”Alice”) h: Human = Alice scala> s.think Søren: I consume memory, therefore I am. scala> f.think Kermit: It aint easy being green. scala> h.legCount res3: Int = 2 scala> f.legCount res4: Int = 4 scala> s.legCount error: value legCount is not a member of Squid
  • 20. Live-coding in REPL with collections
  • 21. Agenda . Introduction to Scala . Object-oriented programming . Objects, classes, and traits . Collections hierarchy . Functional programming . Immutability . Higher-order functions . Algebraic data types . Concurrency . Summary and resources
  • 22. Immutability Identifiers declared as either val (immutable value) or var (mutable variable) scala.collection.immutable vs. scala.collection.mutable scala> import scala.collection.mutable.{Set => MSet} scala> import scala.collection.immutable.Set scala> val s1 = MSet(2,6,7,9) scala> val s2 = Set(3,4,7,8) scala> s1 += 5 res9: s1.type = Set(9, 2, 6, 7, 5) scala> s1 contains 5 res10: Boolean = true scala> s2 += 5 error: reassignment to val
  • 23. Why prefer immutability? Referential transparency — easier for compilers and people to reason about code if f(x) always equals f(x) Concurrency — multiple threads updating a single variable or data structure can corrupt it. Fewer updates make it easier to prevent corruption.
  • 24. Higher-order functions Function values can be passed to other functions, stored in data structures. Syntax of function value: { (x: Int) => x * x } { x => x * 2 } // if type can be inferred { _ * 2 } // if parameter used just once Example from before: name.exists( .isUpper) Define your own control structures! def unless(cond: Boolean)(block: =>Unit) = if(!cond) block unless(3 < 1) { println(”Huh.”) }
  • 25. e flexible ‘for’ comprehension scala> for(i <- 0 to 3; j <- i+1 to 4) yield (i,j) scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)) ‘for’ is based entirely on higher-order functions: (0 to 3).flatMap(i => (i+1 to 4).map(j => (i,j))) // where: flatMap[B](A => TraversableOnce[B]): Seq[B] map[B](A => B): Seq[B]
  • 26. Algebraic data types Based on case classes in Scala: abstract class Tree[A] case class Leaf[A](value: A) extends Tree[A] case class Branch[A]( left: Tree[A], right: Tree[A] ) extends Tree[A] You can construct objects without new All parameters become immutable fields Compiler generates sensible toString, equals, and copy methods. Live-coding binary tree operations
  • 27. Agenda . Introduction to Scala . Object-oriented programming . Objects, classes, and traits . Collections hierarchy . Functional programming . Immutability . Higher-order functions . Algebraic data types . Concurrency . Summary and resources
  • 28. Scala actor asynchronicity scala> import scala.actors.Actor._ scala> actor{println(”TICK”)}; println(”TOCK”) TOCK TICK scala> actor{println(”TICK”)}; println(”TOCK”) TICK TOCK
  • 30. Scala actors Actors are objects that send/receive messages. a ! m sends message m to actor a, and returns immediately (fire and forget). System serializes message receives within actor. react does not block thread, but also does not return. Can arrange computations to follow react using loop, andThen.
  • 31. Scala actor messaging import scala.actors.Actor._ case object Incr case object Get val counter = actor { var n = 0 loop { // repeatedly wait for a message react { // (but don’t block thread) case Incr => n += 1; println(n) case Get => sender ! n } } } counter ! Incr // fire and forget; eventually counter ! Incr // prints ’1’ then ’2’
  • 32. Future power people scala> counter ! Incr scala> counter ! Incr 3 4 scala> val f = counter !! Get f: z.Future[Any] = <function0> scala> f.foreach { case x: Int => println(”Square is ” + x*x) } Square is 16
  • 33. ‘For’ the future Because Future implements standard collection methods like flatMap, you can sequence asynchronous computations with ‘for’ syntax: for(r1 <- act1 !! SomeOperation(x1,x2); r2 <- act2 !! AnotherOperation(r1,y1,y2)) { storeResult(r2) }
  • 34. Resources scala-lang.org typesafe.com Free* e-book: slidesha.re/BnNJu ny-scala meetup