Your SlideShare is downloading. ×
0
Starting with ScalaFrontier Developers MeetupDecember 9th, 2010Boulder, CO                              Derek Chen-Becker ...
Scalas Pedigree Created by Martin Odersky (EPFL), of GJ, and later Javac v5 fame
Scalas History                                                              Scala History                                 ...
More Info on Scala Home page: http://www.scala-lang.org/ Excellent community  scala-user@listes.epfl.ch  irc://chat.freeno...
Scala in Print
Scala in the Real World
Scala and the JVM Compiles to 100% Java Bytecode  Generally works flawlessly with Java  Leverages JIT: performance ±5% of ...
About This Talk Scala 2.8.0+  Significant changes to library  Im still coming up to speed on  them This is not a lecture
Act INo Time Like the Present
The Scala REPL Read, Evaluate, Print, Loop You need a JVM (1.6+ preferred) with “java” in your path or JAVA_HOME set Downl...
Play Along at Home!       http://www.simplyscala.com/
Act IISo, What is Scala?
Three Very Common Keywords val – defines an immutable value or reference var – defines a mutable value def – defines a fun...
Scala is Concerned with Mutability Immutable data structures reduce (but not eliminate) concurrency issues Combined with a...
Scala is Strongly Typed...   val foo : Int = 12   var bar : String = "twelve"   def baz (in : Int) : Double =     in.toDou...
...But Can Usually Figure Types Out  val foo            = 12  var bar               = "twelve"  def baz (in : Int)        ...
Scala is Genericval primes : List[Int] =  List(2,3,5,7,11)scala> primes.grouped(2).toListres16: List[List[Int]] =List(List...
Scala is Object­Oriented      class Foo {        def bar () = {         "bat"        }      }      val f = new Foo
I Mean Really Object­Oriented                           st Primitives are treated as 1 class objects         scala> (12.5)...
Scala is Functionalval greet = (name : String) =>  "Hello, %s!".format(name)greet(“Fred”)res27: String = Hello, Fred!val g...
Scala is Functional Everywheredef doubleMe (f : () => Any) {  println(f()); println(f());}scala>doubleMe(System.nanoTime)1...
Scala is Closurific  def counter (name : String) = {    var i = 0;    { () =>      i += 1      name + ":" + i    }  }
Scala is Concise...public class Person {  private String name;  private int age;    public Person(String name, int age) { ...
...But Maintains Uniform Access case class Person(val name : String,              private var curAge : Int) {   def age = ...
Scala is DSL­Friendly (be reasonable)class   Vector[T](data : Array[T]){  def   + (that : Vector[T]) = {}  def   - (that :...
Scala is Optionalval exists: Option[Int]= Some(42)val notHere: Option[Int] = Nonescala> exists.map(_ * 2).getOrElse(12)res...
Scala Likes Tuples (Heterogeneous)scala> val state = (12, "Empty", RED)state: (Int, java.lang.String, java.awt.Color)= (12...
Scala is XML­Friendly def personToXml(p : Person) =   <person name={p.name}     age={p.age.toString} />
Scala is High­Level...val people = List(Person("Fred", 30),                  Person("Ted", 25),                  Person("E...
Letting You Get to the Real Work// One line of magic...implicit val orderPeople =  Ordering.by((_:Person).age)// ...allows...
Act IIIScala OO Fundamentals
Packages       package net.foo {         ...       }       package net.foo
Importsimport java.io.Fileimport java.net._import java.awt.{Image,  Color => JCol, Dialog => _}
Packages Nest...           package net.foo                  ==           package net {             package foo {          ...
Sometimes in Unexpected Ways (< 2.8)      package net.foo {        import java.net.URL      }
The Scala OO Quadfecta                trait     class               object             case class/               object
Traits Are Good Somewhat analogous to interfaces...trait   Comparable[T] {  def   < (that : T) : Boolean  def   <= (that :...
Traits are Really Awesome ...But they can carry implementationtrait Comparable[T <: Comparable[T]] {    self : T =>  def <...
Traits can be Composedtrait Atrait Btrait Cclass Base extends A with Bwith C
Class Linearization : Base Trait     trait Pet {       def greeting : String       def eat() : Unit     }
Class Linearization : Extension Traitstrait Dog extends Pet {  def greeting = "Woof"  def eat() {...}}trait Mute extends P...
Class Linearization : Composition     class Dingo extends Dog       with Mute  scala> (new Dingo).greeting  res0: java.lan...
Scala Objects “An object definition defines a single object of a new class” (Scala Reference, §5.4    object Friendly {   ...
Objects hold Static Methods object MyApp {   def main (args : Array[String]) {         ...     } }
Objects are Scoped VM Singletons       class Outer {         object Inner {           var foo = "foo"         }       }
Objects as Factoriesobject Person {  def apply(name : String,            age : Int) : Person =    new Person(name,age)}val...
Objects as Factories, Continuedobject Person {  ...  def apply(name : String) : Person =    new Person(name, 1)}val babyFr...
Named and Default Argumentsobject Person {  def apply(name : String,            age : Int = 1) : Person =    new Person(na...
Case Classes (and Objects)case class Car (name : String,                gears : Int)scala> val myCar = Car("Corolla", 4)my...
Case Class Automation Factory method (apply) toString hashCode equals (and therefore ==) Constructor params become vals, c...
Case Class Bonii : Copy scala> val myCar = Car("Corolla", 4) myCar: Car = Car(Corolla,4) scala> val myOtherCar =   myCar.c...
Case Class Bonii : Extractionscala> val myCar = Car("Corolla", 4)myCar: Car = Car(Corolla,4)// “_” here means “dont bother...
Act IVFunctional is Your Friend
Start With Some Basic Functions foreach map flatMap filter exists takeWhile dropWhile
Composing Functions == Power  people.flatMap(first =>    people.filter(_ != first).      map(List(first,_)))
For Comprehensions   for (first <- people;        second <- people          if first != second)     yield List(first,second)
Currying Provide N argument lists, but only use 1 to N-1 of them to define a new function def scaler (factor : Int)       ...
“By Name” Argumentsdef myWhile (condition : => Boolean)            (f : => Unit) {  if (condition) {    f; myWhile(conditi...
“By Name” Use Case : Logging if (logger.isDebugEnabled) {   logger.debug("Foo: " + foo) }
“By Name” Use Case : Logging      THIS if (logger.isDebugEnabled) {   logger.debug("Foo: " + foo) }     SUCKS
“By Name” to the Rescue def debug (msg : => String) {   if (this.debugEnabled) {     println(msg)   } }  https://github.co...
Pattern Matching : Switch on Steroids “case _” here is the default case   def literalMatch (in: Any) {     in match {     ...
Pattern Matching : Alternate Matches Using “|” allows multi-match casesdef literalMatch (in: Any) {  in match {    case 1 ...
Pattern Matching : XMLdef xmlMatch (in : Any) = in match {  case <people>{bar @ _*}</people> =>    bar.foreach(println)  c...
Pattern Matching : Case Classes def caseMatch (a : Any) = a match {   case Person(name, age) =>     println("%s is %d”.   ...
Pattern Matching : Type Matchesdef typeMatch (in: Any) {  in match {    case i : Int => doBar("Int : " + i)    case s : St...
Pattern Matching : Generics  Erasure is not your friend def typeMatch   (in: Any) {   in match {     case ls :   List[Stri...
Pattern Matching : Guards def guardMatch (in: Any) {   in match {     case i : Int        if i > 12 && i < 47 =>         d...
Pattern Matching : Generics Workaround Like duck tape : ugly, but effectivedef typeMatch (in: Any) {  in match {    case l...
More More Info on Scala Home page: http://www.scala-lang.org/ Excellent community  scala-user@listes.epfl.ch  irc://chat.f...
Upcoming SlideShare
Loading in...5
×

Starting with Scala : Frontier Developer's Meetup December 2010

2,158

Published on

Slides from my presentation on getting started with Scala

Published in: Technology

Transcript of "Starting with Scala : Frontier Developer's Meetup December 2010"

  1. 1. Starting with ScalaFrontier Developers MeetupDecember 9th, 2010Boulder, CO Derek Chen-Becker Senior Network Engineer CPI Corporation
  2. 2. Scalas Pedigree Created by Martin Odersky (EPFL), of GJ, and later Javac v5 fame
  3. 3. Scalas History Scala History 2.8.1 2.8.0 2.7.0 2.6.0 2.5.0 2.7.1 - 2.7.7 2.4.0 2.3.0 2.2.0 2.1.0 1.4.0.0 1.3.0.2 1.2.0.0 1.1.1.0 Jan 04 Jan 05 Jan 06 Jan 07 Jan 08 Jan 09 Jan 10
  4. 4. More Info on Scala Home page: http://www.scala-lang.org/ Excellent community scala-user@listes.epfl.ch irc://chat.freenode.net/scala http://scala.sygneca.com/ (Wiki)
  5. 5. Scala in Print
  6. 6. Scala in the Real World
  7. 7. Scala and the JVM Compiles to 100% Java Bytecode Generally works flawlessly with Java Leverages JIT: performance ±5% of Java Full access to existing Java ecosystem CLR (.Net) port in progress
  8. 8. About This Talk Scala 2.8.0+ Significant changes to library Im still coming up to speed on them This is not a lecture
  9. 9. Act INo Time Like the Present
  10. 10. The Scala REPL Read, Evaluate, Print, Loop You need a JVM (1.6+ preferred) with “java” in your path or JAVA_HOME set Download the latest binaries from http://www.scala-lang.org/downloads Unpack wherever, go to bin subdirectory Type “scala<enter>”
  11. 11. Play Along at Home! http://www.simplyscala.com/
  12. 12. Act IISo, What is Scala?
  13. 13. Three Very Common Keywords val – defines an immutable value or reference var – defines a mutable value def – defines a function/method
  14. 14. Scala is Concerned with Mutability Immutable data structures reduce (but not eliminate) concurrency issues Combined with actors make a powerful approach to parallel tasks Strong library and language support
  15. 15. Scala is Strongly Typed... val foo : Int = 12 var bar : String = "twelve" def baz (in : Int) : Double = in.toDouble
  16. 16. ...But Can Usually Figure Types Out val foo = 12 var bar = "twelve" def baz (in : Int) = in.toDouble
  17. 17. Scala is Genericval primes : List[Int] = List(2,3,5,7,11)scala> primes.grouped(2).toListres16: List[List[Int]] =List(List(2, 3), List(5, 7),List(11))
  18. 18. Scala is Object­Oriented class Foo { def bar () = { "bat" } } val f = new Foo
  19. 19. I Mean Really Object­Oriented st Primitives are treated as 1 class objects scala> (12.5).min(47) res17: Double = 12.5 scala> 3825.toHexString res18: String = ef1 scala> 5.isWhitespace res19: Boolean = false
  20. 20. Scala is Functionalval greet = (name : String) => "Hello, %s!".format(name)greet(“Fred”)res27: String = Hello, Fred!val greet = "Hello, %s!".format(_ : String)
  21. 21. Scala is Functional Everywheredef doubleMe (f : () => Any) { println(f()); println(f());}scala>doubleMe(System.nanoTime)15885045173037341588504517365296
  22. 22. Scala is Closurific def counter (name : String) = { var i = 0; { () => i += 1 name + ":" + i } }
  23. 23. Scala is Concise...public class Person { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } case class Person(name : String, VS var age : Int) public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int hashCode() {...} public String toString() {...} public boolean equals() {...}}
  24. 24. ...But Maintains Uniform Access case class Person(val name : String, private var curAge : Int) { def age = curAge def age_= (a : Int) { curAge = a } }
  25. 25. Scala is DSL­Friendly (be reasonable)class Vector[T](data : Array[T]){ def + (that : Vector[T]) = {} def - (that : Vector[T]) = {} ... def ⊗ (that : Vector[T]) = {}}val product = A ⊗ Bval product = A.⊗(B)
  26. 26. Scala is Optionalval exists: Option[Int]= Some(42)val notHere: Option[Int] = Nonescala> exists.map(_ * 2).getOrElse(12)res0: Int = 84scala> notHere.map(_ * 2).getOrElse(12)res1: Int = 12
  27. 27. Scala Likes Tuples (Heterogeneous)scala> val state = (12, "Empty", RED)state: (Int, java.lang.String, java.awt.Color)= (12,Empty,java.awt.Color[r=255,g=0,b=0])scala> val (count, description, color) = statecount: Int = 12description: java.lang.String = Emptycolor: java.awt.Color =java.awt.Color[r=255,g=0,b=0]
  28. 28. Scala is XML­Friendly def personToXml(p : Person) = <person name={p.name} age={p.age.toString} />
  29. 29. Scala is High­Level...val people = List(Person("Fred", 30), Person("Ted", 25), Person("Ed", 41))people.foreach (println)
  30. 30. Letting You Get to the Real Work// One line of magic...implicit val orderPeople = Ordering.by((_:Person).age)// ...allows powerful constructsval (oldest,youngest) = (people.max,people.min)
  31. 31. Act IIIScala OO Fundamentals
  32. 32. Packages package net.foo { ... } package net.foo
  33. 33. Importsimport java.io.Fileimport java.net._import java.awt.{Image, Color => JCol, Dialog => _}
  34. 34. Packages Nest... package net.foo == package net { package foo { ... } }
  35. 35. Sometimes in Unexpected Ways (< 2.8) package net.foo { import java.net.URL }
  36. 36. The Scala OO Quadfecta trait class object case class/ object
  37. 37. Traits Are Good Somewhat analogous to interfaces...trait Comparable[T] { def < (that : T) : Boolean def <= (that : T) : Boolean def > (that : T) : Boolean def >= (that : T) : Boolean}
  38. 38. Traits are Really Awesome ...But they can carry implementationtrait Comparable[T <: Comparable[T]] { self : T => def < (that : T) : Boolean def <= (that : T) = this < that || this == a def > (that : T) = that < this def >= (that : T) = that <= this}
  39. 39. Traits can be Composedtrait Atrait Btrait Cclass Base extends A with Bwith C
  40. 40. Class Linearization : Base Trait trait Pet { def greeting : String def eat() : Unit }
  41. 41. Class Linearization : Extension Traitstrait Dog extends Pet { def greeting = "Woof" def eat() {...}}trait Mute extends Pet { override val greeting = ""}
  42. 42. Class Linearization : Composition class Dingo extends Dog with Mute scala> (new Dingo).greeting res0: java.lang.String =
  43. 43. Scala Objects “An object definition defines a single object of a new class” (Scala Reference, §5.4 object Friendly { var publicInt = 0 def hi = println("Hi!") }
  44. 44. Objects hold Static Methods object MyApp { def main (args : Array[String]) { ... } }
  45. 45. Objects are Scoped VM Singletons class Outer { object Inner { var foo = "foo" } }
  46. 46. Objects as Factoriesobject Person { def apply(name : String, age : Int) : Person = new Person(name,age)}val fred = Person("Fred", 20)
  47. 47. Objects as Factories, Continuedobject Person { ... def apply(name : String) : Person = new Person(name, 1)}val babyFred = Person("Fred")
  48. 48. Named and Default Argumentsobject Person { def apply(name : String, age : Int = 1) : Person = new Person(name,age)}val fredBaby = Person(name = "Fred")
  49. 49. Case Classes (and Objects)case class Car (name : String, gears : Int)scala> val myCar = Car("Corolla", 4)myCar: Car = Car(Corolla,4)scala> myCar.nameres0: String = Corolla
  50. 50. Case Class Automation Factory method (apply) toString hashCode equals (and therefore ==) Constructor params become vals, can be turned into vars
  51. 51. Case Class Bonii : Copy scala> val myCar = Car("Corolla", 4) myCar: Car = Car(Corolla,4) scala> val myOtherCar = myCar.copy(name = "Forester") myOtherCar: Car = Car(Forester,4)
  52. 52. Case Class Bonii : Extractionscala> val myCar = Car("Corolla", 4)myCar: Car = Car(Corolla,4)// “_” here means “dont bother”scala> val Car(_,gears) = myCargears: Int = 4
  53. 53. Act IVFunctional is Your Friend
  54. 54. Start With Some Basic Functions foreach map flatMap filter exists takeWhile dropWhile
  55. 55. Composing Functions == Power people.flatMap(first => people.filter(_ != first). map(List(first,_)))
  56. 56. For Comprehensions for (first <- people; second <- people if first != second) yield List(first,second)
  57. 57. Currying Provide N argument lists, but only use 1 to N-1 of them to define a new function def scaler (factor : Int) (value : Int) = factor * value val times2 = scaler(2) _ times2(12) // == 24
  58. 58. “By Name” Argumentsdef myWhile (condition : => Boolean) (f : => Unit) { if (condition) { f; myWhile(condition)(f) }}
  59. 59. “By Name” Use Case : Logging if (logger.isDebugEnabled) { logger.debug("Foo: " + foo) }
  60. 60. “By Name” Use Case : Logging THIS if (logger.isDebugEnabled) { logger.debug("Foo: " + foo) } SUCKS
  61. 61. “By Name” to the Rescue def debug (msg : => String) { if (this.debugEnabled) { println(msg) } } https://github.com/weiglewilczek/slf4s
  62. 62. Pattern Matching : Switch on Steroids “case _” here is the default case def literalMatch (in: Any) { in match { case 1 => doBar("One") case "test" => doBar("test") case x => doBar("x") case 2.2f => doBar("float") case _ => doBar("lemon curry?") } }
  63. 63. Pattern Matching : Alternate Matches Using “|” allows multi-match casesdef literalMatch (in: Any) { in match { case 1 | 2 | 3 => doBar("One to three") case "this" | "that" => doBar("the other") case _ => doBar("lemon curry?") }}
  64. 64. Pattern Matching : XMLdef xmlMatch (in : Any) = in match { case <people>{bar @ _*}</people> => bar.foreach(println) case _ => // NOOP}
  65. 65. Pattern Matching : Case Classes def caseMatch (a : Any) = a match { case Person(name, age) => println("%s is %d”. format(name,age)) }
  66. 66. Pattern Matching : Type Matchesdef typeMatch (in: Any) { in match { case i : Int => doBar("Int : " + i) case s : String => doBar(s) case _ => // NOOP }}
  67. 67. Pattern Matching : Generics Erasure is not your friend def typeMatch (in: Any) { in match { case ls : List[String] => doBar("danger!") case li : List[Int] => doBar("never happens") case _ => // NOOP } }
  68. 68. Pattern Matching : Guards def guardMatch (in: Any) { in match { case i : Int if i > 12 && i < 47 => doBar("Int : " + i) case _ => // NOOP } }
  69. 69. Pattern Matching : Generics Workaround Like duck tape : ugly, but effectivedef typeMatch (in: Any) { in match { case ls : List[_] if ls.forall(_.isInstanceOf[String]) => doBar("Strings!") case li : List[_] => doBar("Some kind of List") case _ => // NOOP }}
  70. 70. More More Info on Scala Home page: http://www.scala-lang.org/ Excellent community scala-user@listes.epfl.ch irc://chat.freenode.net/scala http://scala.sygneca.com/ (Wiki)
  1. A particular slide catching your eye?

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

×