0
e       ScalaProgramming 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 ...
History   Sun proposes to incorporate Generic Java   Odersky begins design of Scala at EPFL   GJ compiler rele...
Who uses Scala?AppJet            Office DepotEbay              SAICFoursquare        SiemensGridGain          SonyGuardian  ...
Who uses Scala?
One-slide summary: Scala is...ScalableObject-orientedFunctionalCompatibleConciseHigh-levelStatically typedInteractive (REPL)
Scala is... conciseTypical Java class definitionclass MyClass {    private int index;    private String name;    public MyC...
Scala is... high-levelJava: Does a string have an uppercase character?boolean nameHasUpperCase = false;for (int i = 0; i <...
Acknowledgment
Agenda. Introduction to Scala. Object-oriented programming   . Objects, classes, and traits   . Collections hierarch...
Objects and classesIn Java and C++, classes...   . are a template for creating new objects dynamically   . define the met...
Exampleclass ChecksumAccumulator {    private var sum = 0    def add(b: Byte) { sum += b }    def checksum(): Int = ˜(sum ...
Other notable featuresIdentifiers declared as either val (immutable value)or var (mutable variable)Methods introduced by de...
Immutable object exampleclass Rational(n: Int, d: Int) { // main constructor    require(d != 0) // or else IllegalArgument...
TraitsA trait encapsulates method and field definitions,which can then be reused by mixing them intoclasses.A class can mix ...
Traits exampleclass Animal(val name: String) {  override def toString = name}trait Philosophical {  def think {    println...
Traits exampleclass Frog(name: String) extends Animal(name)with HasLegs with Philosophical {  override def think {    prin...
Traits examplescala> val s = new Squids: Squid = Sørenscala> val f = new Frog(”Kermit”)f: Frog = Kermitscala> val h = new ...
Collections hierarchy
Live-coding in REPL with collections
Agenda. Introduction to Scala. Object-oriented programming   . Objects, classes, and traits   . Collections hierarch...
Immutability    Identifiers declared as either val (immutable value)    or var (mutable variable)    scala.collection.immut...
Why prefer immutability?Referential transparency — easier for compilersand people to reason about code if f(x) alwaysequal...
Higher-order functionsFunction values can be passed to other functions,stored in data structures. Syntax of function value...
e flexible ‘for’ comprehensionscala> for(i <- 0 to 3; j <- i+1 to 4) yield (i,j)scala.collection.immutable.IndexedSeq[(Int...
Algebraic data typesBased on case classes in Scala:  abstract class Tree[A]  case class Leaf[A](value: A) extends Tree[A] ...
Agenda. Introduction to Scala. Object-oriented programming   . Objects, classes, and traits   . Collections hierarch...
Scala actor asynchronicityscala> import scala.actors.Actor._scala> actor{println(”TICK”)}; println(”TOCK”)TOCKTICKscala> a...
Concurrency is hard
Scala actorsActors are objects that send/receive messages.a ! m sends message m to actor a, and returnsimmediately (fire an...
Scala actor messagingimport scala.actors.Actor._case object Incrcase object Getval counter = actor {  var n = 0  loop {   ...
Future power peoplescala> counter ! Incrscala> counter ! Incr34scala> val f = counter !! Getf: z.Future[Any] = <function0>...
‘For’ the futureBecause Future implements standard collectionmethods like flatMap, you can sequenceasynchronous computatio...
Resourcesscala-lang.org      typesafe.com      Free* e-book:slidesha.re/BnNJu ny-scala meetup
Upcoming SlideShare
Loading in...5
×

The Scala Programming Language

512

Published on

Introductory talk for LIU students.

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
512
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
26
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "The Scala Programming Language"

  1. 1. e ScalaProgramming Language Christopher League LIU Brooklyn  February 
  2. 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. 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. 4. Who uses Scala?AppJet Office DepotEbay SAICFoursquare SiemensGridGain SonyGuardian SygnecaLinkedIn atchamManaged Gaming TwitterNature WattzOnNovell XebiaNovus Partners XeroxOPower ...
  5. 5. Who uses Scala?
  6. 6. One-slide summary: Scala is...ScalableObject-orientedFunctionalCompatibleConciseHigh-levelStatically typedInteractive (REPL)
  7. 7. Scala is... conciseTypical Java class definitionclass MyClass { private int index; private String name; public MyClass(int index, String name) { this.index = index; this.name = name; }}Equivalent Scala class definitionclass MyClass(index: Int, name: String)
  8. 8. Scala is... high-levelJava: 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)
  9. 9. Acknowledgment
  10. 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. 11. Objects and classesIn 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 objectIn Scala, Classes are responsible only for  and . For , we define a singleton object as a container for static members.
  12. 12. Exampleclass 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. 13. Other notable featuresIdentifiers declared as either val (immutable value)or var (mutable variable)Methods introduced by defArray/map/function syntax are unified: cache(s)Instantiation of generic types: Map[String, Int]if/else returns a valueLast expression of a block is returned, as long asmethod body preceded by ‘=’Very general loop syntax: for(x <- xs) . . . (More on that later...)
  14. 14. Immutable object exampleclass 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. 15. TraitsA trait encapsulates method and field definitions,which can then be reused by mixing them intoclasses.A class can mix in any number of traits, definingstackable modifications.
  16. 16. Traits exampleclass 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 Philosophicaltrait HasLegs { def legCount: Int def jump { println(this + ”: How high?”) }}
  17. 17. Traits exampleclass 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. 18. Traits examplescala> val s = new Squids: Squid = Sørenscala> val f = new Frog(”Kermit”)f: Frog = Kermitscala> val h = new Human(”Alice”)h: Human = Alicescala> s.thinkSøren: I consume memory, therefore I am.scala> f.thinkKermit: It aint easy being green.scala> h.legCountres3: Int = 2scala> f.legCountres4: Int = 4scala> s.legCounterror: value legCount is not a member of Squid
  19. 19. Collections hierarchy
  20. 20. Live-coding in REPL with collections
  21. 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. 22. Immutability Identifiers declared as either val (immutable value) or var (mutable variable) scala.collection.immutable vs. scala.collection.mutablescala> import scala.collection.mutable.{Set => MSet}scala> import scala.collection.immutable.Setscala> val s1 = MSet(2,6,7,9)scala> val s2 = Set(3,4,7,8)scala> s1 += 5res9: s1.type = Set(9, 2, 6, 7, 5)scala> s1 contains 5res10: Boolean = truescala> s2 += 5error: reassignment to val
  23. 23. Why prefer immutability?Referential transparency — easier for compilersand people to reason about code if f(x) alwaysequals f(x)Concurrency — multiple threads updating a singlevariable or data structure can corrupt it. Fewerupdates make it easier to prevent corruption.
  24. 24. Higher-order functionsFunction 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 onceExample from before: name.exists( .isUpper)Define your own control structures!def unless(cond: Boolean)(block: =>Unit) = if(!cond) blockunless(3 < 1) { println(”Huh.”) }
  25. 25. e flexible ‘for’ comprehensionscala> 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. 26. Algebraic data typesBased 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 newAll parameters become immutable fieldsCompiler generates sensible toString, equals,and copy methods.Live-coding binary tree operations
  27. 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. 28. Scala actor asynchronicityscala> import scala.actors.Actor._scala> actor{println(”TICK”)}; println(”TOCK”)TOCKTICKscala> actor{println(”TICK”)}; println(”TOCK”)TICKTOCK
  29. 29. Concurrency is hard
  30. 30. Scala actorsActors are objects that send/receive messages.a ! m sends message m to actor a, and returnsimmediately (fire and forget).System serializes message receives within actor.react does not block thread, but also does notreturn.Can arrange computations to follow react usingloop, andThen.
  31. 31. Scala actor messagingimport scala.actors.Actor._case object Incrcase object Getval 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; eventuallycounter ! Incr // prints ’1’ then ’2’
  32. 32. Future power peoplescala> counter ! Incrscala> counter ! Incr34scala> val f = counter !! Getf: z.Future[Any] = <function0>scala> f.foreach { case x: Int => println(”Square is ” + x*x) }Square is 16
  33. 33. ‘For’ the futureBecause Future implements standard collectionmethods like flatMap, you can sequenceasynchronous computations with ‘for’ syntax:for(r1 <- act1 !! SomeOperation(x1,x2); r2 <- act2 !! AnotherOperation(r1,y1,y2)){ storeResult(r2)}
  34. 34. Resourcesscala-lang.org typesafe.com Free* e-book:slidesha.re/BnNJu ny-scala meetup
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×