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

From Java to Scala

From Java to Scala

Take a first look at Scala, coming from Java-land. Also some ridiculous references to Arrested Development.

James Stephenson

March 01, 2013
Tweet

Other Decks in Programming

Transcript

  1. The Whole Point of This Thing • A quick primer

    on going from Java -> Scala • Identify some of Scala's quirks and concepts • Take a look at a few things from Scala 2.10 • Look at ScalaTest, a robust testing framework Scala all the things! ...Scala all the things?
  2. From Java to Scala • Similarities to Java: ◦ classes,

    abstract classes ◦ static typing ◦ generics...and type erasure :( • Contrasts to Java: ◦ true OO - everything is an object ◦ generics...with reification ◦ traits, singleton objects ◦ case classes (and pattern matching) ◦ multiple inheritance ◦ implicit parameters ◦ explicitly-typed self references & the Cake pattern
  3. Similarities to Java Scala provides standard concrete and abstract class

    concepts: abstract class SeaworthyVessel { ... } class TheSeaward extends SeaworthyVessel { ...} Statically typed, annotations, generics and such, just different syntax...yay. (apologies to those who aren't Arrested Development fans, this could be a confusing presentation for you...)
  4. Scala OO: Contrasts with Java • Everything public unless explicitly

    non-public • Everything actually is an object (even arrays) > "Op!upvdijoh\"".map (_.toInt.-(1).toChar) result: String = "No touching!" • Singleton objects object BluthCompany { def apply(...) = ... } • Case classes, not POJOs case class BusterSaying(saying: String) BusterSaying("Hey brother!") ◦ Also used for pattern matching
  5. Generics - Overcoming Type Erasure • More complete support for

    generics • Type erasure still an issue ◦ Side-effect of running on JVM • Can be overcome using manifests to reify types class B extends A def x[T <: A](a: Array[T])(implicit m: Manifest[T]) = m.runtimeClass x(new Array[B](1)) // = class B
  6. Implicit Parameters def report(x: String)(implicit reporter: String => Unit) =

    reporter(x) Arguments that are eligible to be passed to an implicit parameter fall into two categories: ◦ First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter. ◦ Second, eligible are also all members of companion modules of the implicit parameter's type that are labeled implicit. http://www.scala-lang.org/node/114
  7. Traits & Multiple Inheritance • Traits, not interfaces ◦ More

    like abstract class, but used as "mixin" • Multiple inheritance possible via mixing-in traits • What about the "diamond problem"? ◦ Solved in Scala by resolving right-to-left trait A trait B extends A trait C extends A class D extends B with C • Resolution order in D: D, C, A, B, A ◦ Reduces down to D, C, B, A
  8. Explicitly Typed Self References Declare type of this (or another

    name) explicitly: trait MoneyAdvice { def giveAdvice = "There's always money in the banana stand" } class GeorgeBluth { this: MoneyAdvice => // defined in Money def fatherlyAdvice = this.giveAdvice } (new GeorgeBluth with MoneyAdvice).fatherlyAdvice But, why? It can be a means of object composition
  9. Cake Pattern Use dependencies in Scala by "layering" An idea

    devised by Jonas Bonér (http://goo.gl/C62B2): trait UserRepositoryComponent { val userRepository: UserRepository class UserRepository { ... } } trait UserServiceComponent { this: UserRepositoryComponent => val userService: UserService class UserService { // Code uses userRepository ... } }
  10. Cake Pattern - Usage // Runtime: object ComponentRegistry extends UserServiceComponent

    with UserRepositoryComponent { val userRepository = new UserRepository val userService = new UserService } // Testing: trait UserServiceTestingEnvironment extends UserServiceComponent with UserRepositoryComponent with MockitoSugar { val userRepository = mock[UserRepository] val userService = mock[UserService ] } class UserServiceTest with UserServiceTestingEnvironment { ... }
  11. Cake Pattern - Pros & Cons Pros: • Object composition

    using Scala-specific syntax • Module-based application composition • Allows for test mocking Cons: • Quite verbose ◦ Need to wrap all injectable classes in component traits (is this Java or something?) • Must mix in all required traits ◦ Several components each with dependencies...very cumbersome if not organized properly The point? Don't just use it because it's from a blog, without thinking about why you should, or if you really need to...
  12. Scala 2.10 - What's New? • Value Classes ◦ A

    class may now extend AnyVal to make it behave like a struct type (restrictions apply): class Wrapper(val underlying: Int) extends AnyVal ◦ Avoids costly object allocation in instances where class wraps a simple value ◦ Use cases include adding extension methods on value types and for type-correctness • Implicit Classes ◦ implicit modifier now also applies to class definitions to reduce the boilerplate of implicit wrappers ◦ Implicitly extends types
  13. Scala 2.10 - Continued • String Interpolation (finally...) val where

    = "the banana stand" println(s"there's always money in ${where}!") • Futures/Promises (used to be from Akka) ◦ Asynchronously get some JSON: for (req <- WS.url(restApiUrl).get()) yield (req.json \ "users").as[List[User]] • Dynamic / applyDynamic class CanHazDynamic extends Dynamic { ... } val x = new CanHazDynamic ◦ x.foo becomes x.applyDynamic("foo") • Removed core Actor framework; use Akka instead!
  14. ScalaTest Overview • ScalaTest is your typical unit testing, integration

    testing, and BDD framework all rolled into one • Allows to choose a style of test for those who are... ◦ new to unit testing ◦ used to JUnit-style testing ◦ used to RSpec-style testing ◦ looking for a good BDD framework ◦ want to write properties-based specs ◦ looking for complete freedom in how they write tests