val artist: Artist = maybeArtist getOrElse(defaultArtist) val maybeArtist: Option[Artist] = Option(getArtist()) Providing a Default Value Java Integration
For Comprehensions val asyncFilm = for { artist <- getAsyncArtist film <- getAsyncLastFilm(artist.name) } yield (film) asyncFilm map (film => film.print())
slick -> http://slick.typesafe.com/ doobie -> https://github.com/tpolecat/doobie Pure functional JDBC layer for Scala mvessel -> https://github.com/47deg/mvessel JDBC driver written in Scala The main goal is to allow the use of ORMs in Android
val xa = DriverManagerTransactor[IO]( "org.postgresql.Driver", "jdbc:postgresql:world", "postgres", "" ) case class Country(code: String, name: String, population: Long) def find(n: String): ConnectionIO[Option[Country]] = sql"select code, name from country where name = $n”.query[Country].option find("France").transact(xa).unsafePerformIO Some(Country(FRA, France)) Doobie Sample
Higher-order function • Takes one or more functions as arguments • Returns a function as its result val f1: (Int) => String = (myInt) => myInt.toString def myFunc(f: (Int) => String) = { println(f(2)) }
def toYesOrNo(choice: Int): String = choice match { case 1 => "yes" case 0 => "no" case _ => "error" } Traditional approach def get(animal: Animal): String = animal match { case cat: Cat => “I’m a cat: ” + cat.toString case dog: Dog => “I’m a dog: ” + dog.toString case _ => “Other animal" } Typed pattern
case class Developer(name: String, lang: String) def developer(dev: Developer): String = dev match { case Developer(_, “scala”) => “Good Dev" case Developer(“Jorge Barroso”, _) => “The best" case _ => “Java Developers" } Cases Classes def developer(dev: Developer): String = dev match { case Developer(_, “scala”) => “Good Dev" case Developer(name, _) if name.contains(“Jorge”) => “The best" case _ => “Java Developers" } If statements
No pattern matching, but powerful “when” val cost = when(x) { in 1..10 -> "cheap" in 10..100 -> "regular" in 100..1000 -> "expensive" in specialValues -> "special value!" else -> "not rated" }
• Slower (Scala Compiler + Proguard) • Size matters (+ ~2.8 M) Compile Take your time to setup your SBT • Incremental compiler • Continuous build and test