Easy Dependency Injection in Play Framework with Scaldi
In this post I would like to make small introduction to Scaldi and show you how easy it is to use it together with Play. Scaldi is dependency injection library for Scala. It’s very lightweight (without any dependencies) and provides nice Scala DSL for binding dependencies and injecting them. It’s more dynamic approach to do dependency injection in comparison to the cake pattern, because not everything is checked at the compile time. This can be seen as an disadvantage, but I personally believe, that there is place for this approach. It can be vary useful in many circumstances and many people can find it more natural (and easy), especially if they are coming from Java background.
There are only 3 most important traits that you need to know, in order to make dependency injection with Scaldi:
Injector - it’s a container for the bindings, that you have defined in the module.
Module - gives you nice syntax to create bindings with bind and binding. Module also extends Injector trait and implicit Injector instance always available when you are defining your bindings
Injectable - the only responsibility of this trait is to provide you with inject function (so it just provides nice syntax for injecting dependencies). It’s important to understand, that it’s the only the purpose of it. So it completely stateless and knows nothing about actual bindings you have defined in the module. In order to actually find and inject dependencies, inject function always takes an implicit parameter of type Injector
Regular Expressions Interpolation in Pattern Matching
With introduction of string interpolation in Scala 2.10 we finally got a feature, that many modern languages already have. What made me extremely exited though, is the fact, how good this feature was integrated into the language and how customizable it is. In this post I would like to show you some examples of it. I will not concentrate on explaining how exactly it works, but instead I will show you one very cool application of it, which I found recently. It combines string interpolation with regular expressions. What is especially interesting is the way you can use it in the pattern matching expressions.