SlideShare a Scribd company logo
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 (20)

Spark SQL Bucketing at Facebook
 Spark SQL Bucketing at Facebook Spark SQL Bucketing at Facebook
Spark SQL Bucketing at Facebook
Databricks
 
Apache kafka 확장과 응용
Apache kafka 확장과 응용Apache kafka 확장과 응용
Apache kafka 확장과 응용
JANGWONSEO4
 
Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...
Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...
Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...
ScyllaDB
 
DataOpsbarcelona 2019: Deep dive into MySQL Group Replication... the magic e...
DataOpsbarcelona 2019:  Deep dive into MySQL Group Replication... the magic e...DataOpsbarcelona 2019:  Deep dive into MySQL Group Replication... the magic e...
DataOpsbarcelona 2019: Deep dive into MySQL Group Replication... the magic e...
Frederic Descamps
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
Gephi Consortium
 
Common Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta LakehouseCommon Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta Lakehouse
Databricks
 
E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...
E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...
E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...
Hiroshi Sekiguchi
 
Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache Cassandra
Robert Stupp
 
RediSearch
RediSearchRediSearch
RediSearch
Dvir Volk
 
Qlik Replicateでのタスクの定義と管理
Qlik Replicateでのタスクの定義と管理Qlik Replicateでのタスクの定義と管理
Qlik Replicateでのタスクの定義と管理
QlikPresalesJapan
 
Delta Lake: Optimizing Merge
Delta Lake: Optimizing MergeDelta Lake: Optimizing Merge
Delta Lake: Optimizing Merge
Databricks
 
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
SANG WON PARK
 
Automate Your Kafka Cluster with Kubernetes Custom Resources
Automate Your Kafka Cluster with Kubernetes Custom Resources Automate Your Kafka Cluster with Kubernetes Custom Resources
Automate Your Kafka Cluster with Kubernetes Custom Resources
confluent
 
Building Notebook-based AI Pipelines with Elyra and Kubeflow
Building Notebook-based AI Pipelines with Elyra and KubeflowBuilding Notebook-based AI Pipelines with Elyra and Kubeflow
Building Notebook-based AI Pipelines with Elyra and Kubeflow
Databricks
 
Tuning Autovacuum in Postgresql
Tuning Autovacuum in PostgresqlTuning Autovacuum in Postgresql
Tuning Autovacuum in Postgresql
Mydbops
 
Introduction to Greenplum
Introduction to GreenplumIntroduction to Greenplum
Introduction to Greenplum
Dave Cramer
 
Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...
Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...
Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...
DataStax
 
Qlik Replicate のインストール
Qlik Replicate のインストールQlik Replicate のインストール
Qlik Replicate のインストール
QlikPresalesJapan
 
Qlik Replicateでのレプリケーション・タスクの監視と制御
Qlik Replicateでのレプリケーション・タスクの監視と制御Qlik Replicateでのレプリケーション・タスクの監視と制御
Qlik Replicateでのレプリケーション・タスクの監視と制御
QlikPresalesJapan
 
Real-Time Analytics at Uber Scale
Real-Time Analytics at Uber ScaleReal-Time Analytics at Uber Scale
Real-Time Analytics at Uber Scale
SingleStore
 
Spark SQL Bucketing at Facebook
 Spark SQL Bucketing at Facebook Spark SQL Bucketing at Facebook
Spark SQL Bucketing at Facebook
Databricks
 
Apache kafka 확장과 응용
Apache kafka 확장과 응용Apache kafka 확장과 응용
Apache kafka 확장과 응용
JANGWONSEO4
 
Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...
Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...
Use ScyllaDB Alternator to Use Amazon DynamoDB API, Everywhere, Better, More ...
ScyllaDB
 
DataOpsbarcelona 2019: Deep dive into MySQL Group Replication... the magic e...
DataOpsbarcelona 2019:  Deep dive into MySQL Group Replication... the magic e...DataOpsbarcelona 2019:  Deep dive into MySQL Group Replication... the magic e...
DataOpsbarcelona 2019: Deep dive into MySQL Group Replication... the magic e...
Frederic Descamps
 
Common Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta LakehouseCommon Strategies for Improving Performance on Your Delta Lakehouse
Common Strategies for Improving Performance on Your Delta Lakehouse
Databricks
 
E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...
E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...
E34 : [JPOUG Presents] Oracle Database の隠されている様々な謎を解くセッション「なーんでだ?」再び @ db tec...
Hiroshi Sekiguchi
 
Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache Cassandra
Robert Stupp
 
Qlik Replicateでのタスクの定義と管理
Qlik Replicateでのタスクの定義と管理Qlik Replicateでのタスクの定義と管理
Qlik Replicateでのタスクの定義と管理
QlikPresalesJapan
 
Delta Lake: Optimizing Merge
Delta Lake: Optimizing MergeDelta Lake: Optimizing Merge
Delta Lake: Optimizing Merge
Databricks
 
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...Apache kafka performance(throughput) - without data loss and guaranteeing dat...
Apache kafka performance(throughput) - without data loss and guaranteeing dat...
SANG WON PARK
 
Automate Your Kafka Cluster with Kubernetes Custom Resources
Automate Your Kafka Cluster with Kubernetes Custom Resources Automate Your Kafka Cluster with Kubernetes Custom Resources
Automate Your Kafka Cluster with Kubernetes Custom Resources
confluent
 
Building Notebook-based AI Pipelines with Elyra and Kubeflow
Building Notebook-based AI Pipelines with Elyra and KubeflowBuilding Notebook-based AI Pipelines with Elyra and Kubeflow
Building Notebook-based AI Pipelines with Elyra and Kubeflow
Databricks
 
Tuning Autovacuum in Postgresql
Tuning Autovacuum in PostgresqlTuning Autovacuum in Postgresql
Tuning Autovacuum in Postgresql
Mydbops
 
Introduction to Greenplum
Introduction to GreenplumIntroduction to Greenplum
Introduction to Greenplum
Dave Cramer
 
Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...
Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...
Replication and Consistency in Cassandra... What Does it All Mean? (Christoph...
DataStax
 
Qlik Replicate のインストール
Qlik Replicate のインストールQlik Replicate のインストール
Qlik Replicate のインストール
QlikPresalesJapan
 
Qlik Replicateでのレプリケーション・タスクの監視と制御
Qlik Replicateでのレプリケーション・タスクの監視と制御Qlik Replicateでのレプリケーション・タスクの監視と制御
Qlik Replicateでのレプリケーション・タスクの監視と制御
QlikPresalesJapan
 
Real-Time Analytics at Uber Scale
Real-Time Analytics at Uber ScaleReal-Time Analytics at Uber Scale
Real-Time Analytics at Uber Scale
SingleStore
 

Viewers also liked (8)

Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
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
3Pillar Global
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
Martin Odersky
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
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
3Pillar Global
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
AnsviaLab
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Ad

Similar to The Scala Programming Language (20)

Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
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
Derek Chen-Becker
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
(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 curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Raúl Raja Martínez
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
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
Derek 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 Programmers
Eric Pederson
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Ad

More from league (7)

On the Edge, 2013
On the Edge, 2013On the Edge, 2013
On the Edge, 2013
league
 
On the edge
On the edgeOn the edge
On the edge
league
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
league
 
Programming Android
Programming AndroidProgramming Android
Programming Android
league
 
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 Patterns
league
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
On the Edge, 2013
On the Edge, 2013On the Edge, 2013
On the Edge, 2013
league
 
On the edge
On the edgeOn the edge
On the edge
league
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
league
 
Programming Android
Programming AndroidProgramming Android
Programming Android
league
 
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 Patterns
league
 
Monadologie
MonadologieMonadologie
Monadologie
league
 

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