The Scala Programming Language
Upcoming SlideShare
Loading in...5
×
 

The Scala Programming Language

on

  • 681 views

Introductory talk for LIU students.

Introductory talk for LIU students.

Statistics

Views

Total Views
681
Slideshare-icon Views on SlideShare
678
Embed Views
3

Actions

Likes
0
Downloads
11
Comments
0

1 Embed 3

http://dschool.co 3

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    The Scala Programming Language The Scala Programming Language Presentation Transcript

    • 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 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 DepotEbay SAICFoursquare SiemensGridGain SonyGuardian SygnecaLinkedIn atchamManaged Gaming TwitterNature WattzOnNovell XebiaNovus Partners XeroxOPower ...
    • 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 MyClass(int index, String name) { this.index = index; this.name = name; }}Equivalent Scala class definitionclass MyClass(index: Int, name: String)
    • 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)
    • 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 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.
    • 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 }
    • 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...)
    • 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)}
    • 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.
    • 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?”) }}
    • 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
    • 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
    • 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.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
    • 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.
    • 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.”) }
    • 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]
    • 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
    • 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 asynchronicityscala> import scala.actors.Actor._scala> actor{println(”TICK”)}; println(”TOCK”)TOCKTICKscala> actor{println(”TICK”)}; println(”TOCK”)TICKTOCK
    • Concurrency is hard
    • 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.
    • 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’
    • 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
    • ‘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)}
    • Resourcesscala-lang.org typesafe.com Free* e-book:slidesha.re/BnNJu ny-scala meetup