starting with scala : frontier developer's meetup december 2010

Download Starting with Scala : Frontier Developer's Meetup December 2010

Post on 10-May-2015

2.142 views

Category:

Technology

2 download

Embed Size (px)

DESCRIPTION

Slides from my presentation on getting started with Scala

TRANSCRIPT

  • 1.Starting with ScalaFrontier Developers MeetupDecember 9th, 2010Boulder, CODerek Chen-BeckerSenior Network EngineerCPI Corporation

2. ScalasPedigree Created by Martin Odersky (EPFL), of GJ, and later Javac v5 fame 3. ScalasHistoryScala History 2.8.1 2.8.02.7.0 2.6.0 2.5.0 2.7.1 - 2.7.72.4.02.3.0 2.2.0 2.1.0 1.4.0.0 1.3.0.2 1.2.0.01.1.1.0 Jan 04 Jan 05 Jan 06 Jan 07Jan 08Jan 09Jan 10 4. MoreInfoonScala Home page: http://www.scala-lang.org/ Excellent communityscala-user@listes.epfl.chirc://chat.freenode.net/scalahttp://scala.sygneca.com/ (Wiki) 5. ScalainPrint 6. ScalaintheRealWorld 7. ScalaandtheJVM Compiles to 100% Java BytecodeGenerally works flawlessly with JavaLeverages JIT: performance 5% ofJava Full access to existing Java ecosystem CLR (.Net) port in progress 8. AboutThisTalk Scala 2.8.0+Significant changes to libraryIm still coming up to speed onthem This is not a lecture 9. Act INo Time Like the Present 10. TheScalaREPL 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 11. PlayAlongatHome! http://www.simplyscala.com/ 12. Act IISo, What is Scala? 13. ThreeVeryCommonKeywords val defines an immutable value or reference var defines a mutable value def defines a function/method 14. ScalaisConcernedwithMutability 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. ScalaisStronglyTyped... val foo : Int = 12 var bar : String = "twelve" def baz (in : Int) : Double = in.toDouble 16. ...ButCanUsuallyFigureTypesOutval foo= 12var bar = "twelve"def baz (in : Int)=in.toDouble 17. ScalaisGenericval 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. ScalaisObjectOrientedclass Foo {def bar () = { "bat"}}val f = new Foo 19. IMeanReallyObjectOriented 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. ScalaisFunctionalval greet = (name : String) =>"Hello, %s!".format(name)greet(Fred)res27: String = Hello, Fred!val greet ="Hello, %s!".format(_ : String) 21. ScalaisFunctionalEverywheredef doubleMe (f : () => Any) {println(f()); println(f());}scala>doubleMe(System.nanoTime)15885045173037341588504517365296 22. ScalaisClosurificdef counter (name : String) = {var i = 0;{ () =>i += 1name + ":" + i}} 23. ScalaisConcise...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. ...ButMaintainsUniformAccess case class Person(val name : String,private var curAge : Int) { def age = curAge def age_= (a : Int) { curAge = a } } 25. ScalaisDSLFriendly(bereasonable)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. ScalaisOptionalval 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. ScalaLikesTuples(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. ScalaisXMLFriendly def personToXml(p : Person) = 29. ScalaisHighLevel...val people = List(Person("Fred", 30),Person("Ted", 25),Person("Ed", 41))people.foreach (println) 30. LettingYouGettotheRealWork// One line of magic...implicit val orderPeople =Ordering.by((_:Person).age)// ...allows powerful constructsval (oldest,youngest) =(people.max,people.min) 31. Act IIIScala OO Fundamentals 32. Packages package net.foo { ... } package net.foo 33. Importsimport java.io.Fileimport java.net._import java.awt.{Image,Color => JCol, Dialog => _} 34. PackagesNest... package net.foo== package net { package foo { ... } } 35. SometimesinUnexpectedWays(= (that : T) : Boolean} 38. TraitsareReallyAwesome ...But they can carry implementationtrait Comparable[T def < (that : T) : Booleandef (that : T) = that < thisdef >= (that : T) = that (new Dingo).greetingres0: java.lang.String = 43. ScalaObjects An object definition defines a single object of a new class (Scala Reference, 5.4object Friendly {var publicInt = 0def hi = println("Hi!")} 44. ObjectsholdStaticMethods object MyApp { def main (args : Array[String]) { ... } } 45. ObjectsareScopedVMSingletons class Outer { object Inner { var foo = "foo" } } 46. ObjectsasFactoriesobject Person {def apply(name : String,age : Int) : Person =new Person(name,age)}val fred = Person("Fred", 20) 47. ObjectsasFactories,Continuedobject Person {...def apply(name : String) : Person =new Person(name, 1)}val babyFred = Person("Fred") 48. NamedandDefaultArgumentsobject Person {def apply(name : String,age : Int = 1) : Person =new Person(name,age)}val fredBaby = Person(name = "Fred") 49. CaseClasses(andObjects)case class Car (name : String,gears : Int)scala> val myCar = Car("Corolla", 4)myCar: Car = Car(Corolla,4)scala> myCar.nameres0: String = Corolla 50. CaseClassAutomation Factory method (apply) toString hashCode equals (and therefore ==) Constructor params become vals, can be turned into vars 51. CaseClassBonii: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. CaseClassBonii:Extractionscala> val myCar = Car("Corolla", 4)myCar: Car = Car(Corolla,4)// _ here means dont botherscala> val Car(_,gears) = myCargears: Int = 4 53. Act IVFunctional is Your Friend 54. StartWithSomeBasicFunctions foreach map flatMap filter exists takeWhile dropWhile 55. ComposingFunctions==Powerpeople.flatMap(first =>people.filter(_ != first).map(List(first,_))) 56. ForComprehensions for (first Unit) {if (condition) {f; myWhile(condition)(f)}} 59. ByNameUseCase:Logging if (logger.isDebugEnabled) { logger.debug("Foo: " + foo) } 60. ByNameUseCase:LoggingTHIS if (logger.isDebugEnabled) { logger.debug("Foo: " + foo) } SUCKS 61. ByNametotheRescue def debug (msg : => String) { if (this.debugEnabled) { println(msg) } }https://github.com/weiglewilczek/slf4s 62. PatternMatching:SwitchonSteroids 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. PatternMatching:AlternateMatches 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. PatternMatching:XMLdef xmlMatch (in : Any) = in match {case {bar @ _*} =>bar.foreach(println)case _ => // NOOP} 65. PatternMatching:CaseClasses def caseMatch (a : Any) = a match { case Person(name, age) => println("%s is %d. format(name,age)) } 66. PatternMatching:TypeMatchesdef typeMatch (in: Any) {in match {case i : Int => doBar("Int : " + i)case s : String => doBar(s)case _ => // NOOP}} 67. PatternMatching:GenericsErasure 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. PatternMatching:Guards def guardMatch (in: Any) { in match { case i : Intif i > 12 && i < 47 => doBar("Int : " + i) case _ => // NOOP } } 69. PatternMatching:GenericsWorkaround 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. MoreMoreInfoonScala Home page: http://www.scala-lang.org/ Excellent communityscala-user@listes.epfl.chirc://chat.freenode.net/scalahttp://scala.sygneca.com/ (Wiki)