Between Zero & Hero - Scala Tips and Tricks for the intermediate Scala developer
I gave this updated version of my "Lessons Learned" talk at the Scala.IO conference in Paris on October 24th 2013. It tries to introduce some "just beyond beginner"-level Scala features in a quick-fire way. It ended up a bit too quick on the day :)
Use Case: simplification Type Aliases Sometimes type signatures get in the way of understanding A few well-placed type aliases can hide that complexity And it saves a lot of typing too
Explanation: Auto-lifted Partial Functions When reading method signatures such as these: You would think that you need to do this: But in fact Scala allows you to do this:
The NoStackTrace Trait Explanation: Remember this? Huh? For use in scala.util.Failure and other places that require Throwables without necessarily needing stack traces
Type Classes Definition: "A type of Adapter that uses Scala’s implicits to add some extra capabilities to an existing type without direct coupling" “Sort of like @Autowire for types...” - Some guy on the internet - Me
Type Classes Problem: It would be nice if there were an easy way to constrain T to something that can be (de)serialized or indexed without forcing users to extend their domain classes from my traits How do I turn a T into a RiakValue?
Type Classes Making the parameter implicit is (most of) the big trick that turns RiakSerializer into a type class Step 2: use them as implicit parameters
Context Bounds & Implicitly Explanation: Implicit parameters that look like this: Can also be written like this: You can always get a reference to any implicit value or parameter using the implicitly[T] function
Why? Low Priority Default Implicits You want to provide some default implementations of your type classes so your users don’t have to do all the work. The companion object for your type class is the perfect place for this, but....
Solution: Use the Scala rules for resolving implicits to your advantage by making sure your defaults have the lowest possible implicit resolution priority This is a very common trick in Scala libraries Low Priority Default Implicits
http://www.slideshare.net/DerekWyatt1/scala-implicits-not-to-be-feared http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html Type Classes Further Reading: