This is a talk I gave for the Dutch Scala Enthusiasts meetup on April 25th 2013. It describes some intermediate-level Scala tips and tricks that I learned while developing an open source Scala library.
From A to L Designing Scala Libraries Scala features, patterns, idioms, tips and tricks I picked up while reading other people’s library source code and writing my own SCALAPENOS
Where do I get these skillz? Writing lots of application code Making lots of mistakes Reading LOTS of Scala library source code Mostly: Spray source code
Why? Most of the existing Scala Riak client libraries were dead projects None of them were compatible with Scala 2.10 or Akka 2.1.x None of them were non-blocking The official Java client library has a very (ugly) Java-ish API The official Java client library is blocking It was the Christmas holidays and I needed a new hobby project
Design Goals: It should be completely non-blocking It should integrate well with Akka It should be simple and easy to use It should be easy to extend The API should be idiomatic Scala
Wikipedia Definition: "... a type system construct that supports ad-hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types" Ehm...?
The Problem: It would be nice if there were an easy way to constrain T to something that can be serialized and indexed without forcing users to extend their domain classes from my traits How do I turn a T into a RiakValue?
Context Bounds: Can also be written using a Context Bound: And if you do need a reference to the unnamed implicit parameter, you can get one using implicitly(...)
The Problem: error: ambiguous implicit values: both ... and ... match expected ... When the Scala compiler tells you: When two implicits get resolved at the same level the compiler cannot choose between them
Implicit Resolution Rules: Implicits Defined in Current Scope Explicit Imports Wildcard Imports Same Scope in Other Files Companion Objects of a Type Implicit scope of an argument’s type Implicit scope of type arguments Outer Objects for Nested Types Other Dimensions Don’t worry, it’s easier than it sounds!
When [T] doesn’t make sense: When information about a type is only useful on the inside, don’t bother your users with a type parameter and use abstract types instead