Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Crash course in Scala

Crash course in Scala

Avatar for rufusdingo

rufusdingo

July 19, 2012
Tweet

Other Decks in Programming

Transcript

  1. what is Scala • first released in 2003 • current

    release 2.9.2 • static typing • has object-oriented and functional language features • runs on the JVM (or CLR for .NET) • released under a BSD licence Thursday, 19 July 12
  2. ...collections map val numbers = List(1, 2, 3, 4) numbers.map((i:

    Int) => i * 2) res1: List[Int] = List(2, 4, 6, 8) Thursday, 19 July 12
  3. ... foreach // like .map with side effect val numbers

    = List(1, 2, 3, 4) numbers.foreach((i: Int) => print(i + ",")) 1,2,3,4, Thursday, 19 July 12
  4. ... filter val numbers = List(1, 2, 3, 4) numbers.filter((i

    : Int) => i % 2 ==0) res1: List[Int] = List(2, 4) Thursday, 19 July 12
  5. ... and more • List(1, 2, 3).zip(List("a", "b", "c")) res1:

    List[(Int, String)] = List((1,a), (2,b), (3,c)) • List(1, 3, 5, 7, 9).partition((i: Int) => i > 5) res1: (List[Int], List[Int]) = (List(7, 9),List(1, 3, 5)) • List(1,2,3,4,5).find((i: Int) => i > 3) res1: Option[Int] = Some(4) • and can be chained... numbers.filter(...).map(...) Thursday, 19 July 12
  6. option // slightly nicer nulls def optionTest(name: Option[String]) = {

    name.foreach(println(_)) name.getOrElse("no name") } optionTest(None) res1: String = no name optionTest(Option("Phillip")) Phillip res16: String = Phillip Thursday, 19 July 12
  7. classes abstract class Animal { val legs:Int val noise:String def

    makeNoise() = println(noise) } // inheritance class Cat extends Animal { val legs = 4 val noise = "Meow" } Thursday, 19 July 12
  8. traits (mixins) // like interfaces in Java trait Alive {

    def walk } // but can also do stuff! trait Alive { def walk = println("pad pad") } class Dog extends Animal with Alive { ... } // or apply traits on the fly val kitty = new Cat with Alive Thursday, 19 July 12
  9. packages // all classes in file go in this package

    package com.zestia // import a single class import java.util.List // import everything in java.util import java.util._ // alias an import import java.util.{ArrayList => JavaList} // import statics from Math import java.lang.Math._ Thursday, 19 July 12
  10. type bounds class Coded(var code:String) { ... } class Encoded(...)

    extends Coded(code) { ... } class Sorter[T <: Coded](list:List[T]) { def regular = list def sorted = list.sort((a,b) => a.code.compare(b.code) < 0) } Thursday, 19 July 12
  11. duck typing // use a trait you slackers! - otherwise...

    // requires an object that has method “getById(id:Int)” // which returns an object with public var called “name” def showName(dao:{ def getById(id:Int):{var name:String} }, id:Int) { var record = dao.getById(id) println(record.name) } Thursday, 19 July 12
  12. implicit conversions // Like Open Classes by Type Safe implicit

    def Squared(int : Int) = new { def square() = { int * int } } 2.square res1: Int = 4 Thursday, 19 July 12
  13. exceptions class Exceptions { def doSomething = { try {

    boom() } catch { case ioe: IOException => log.info("IOException; PANIC",ioe) // any other exception will get through as if we didn't try/catch } finally { // tidy up resources, always run even if there is an exception } } } Thursday, 19 July 12
  14. match val times = 1 times match { case 1

    => "one" case 2 => "two" case _ => "some other number" } res1: java.lang.String = one Thursday, 19 July 12
  15. regular expressions and match val date = "11/01/2010" val Date

    = """(\d\d)/(\d\d)/(\d\d\d\d)""".r date match { case Date(day, "01", year) => "Jan " + day case Date(day, "02", year) => "Feb " + day case _ => "a date" } res1: java.lang.String = Feb 11 val Date(day, month, year) = date // outputs 3 vals day: String = 11 month: String = 02 year: String = 2010 Thursday, 19 July 12
  16. futures def task(time: Long, name: String) = { Thread.sleep(time); name

    } // kick back and relax - we’re blocking for 2000 ms Futures.awaitAll(2000, future { task(1000, "hard!") }, future { task(10, "easy!") }, future { task(4000, "i cannae do it captain" ) }, future { task(1000, "tricky!") }, future { task(1000, "difficult!") } ) res1: List(Some(hard!), Some(easy!), None, Some(tricky!), Some(difficult!)) Thursday, 19 July 12
  17. actors object AnActor extends Actor { def act() { while

    (true) { receive { case s: String => { Thread.sleep(1000) println("To be or not to " + s) } case _ => println("?") } } } } AnActor.start AnActor ! "be" AnActor ! "be" AnActor ! "be. That is the questions" To be or not to be To be or not to be To be or not to be. That is the question Thursday, 19 July 12
  18. simple build tool • a.k.a. sbt • dependency management (using

    ivy) • standard project layout • run, compile, test, publish... • add additional tasks using Scala • access to Scala console Thursday, 19 July 12
  19. plays nice with Java* // support JavaBeans setters and getters

    import scala.reflect.{BeanProperty, BooleanBeanProperty} class PersonBean { @BeanProperty var name: String = "Foo" var address: String = "Bar" @BooleanBeanProperty val awesome = true } val dude = new PersonBean dude.getName // okay dude.getAddress // fail dude.isAwesome // awesome! Thursday, 19 July 12
  20. plays nice with Java* // give scala’s functional features to

    // java collections val javaList = new java.util.ArrayList() javaList.foreach(...) // fail :( import collection.JavaConversions._ javaList.foreach(...) // ftw :) Thursday, 19 July 12
  21. Scripting ~ joe$ cat script.sh #!/bin/sh exec scala $0 $@

    !# // Say hello to the first argument println("Hello, " + args(0) + "!") ~ joe$ chmod +x script.sh ~ joe$ ./script.sh joe Hello, joe! Thursday, 19 July 12