Scala Dependency Injection – The Cake Pattern

The cake pattern is an important pattern to do dependency injection in Scala. It is explained in various blog posts on the web, for example by Jason Arhart, by Mark Harrison and by Eran Medan. And I am sure there are dozens of other places.

However, I want to write an explanation myself, mostly for my own benefit. But before we dive into the cake pattern, we first need to understand the so-called ‘self-type’ in Scala.

What is a Self-Type?

You might actually have seen it in Scala code before. A self-type is used to let a class state what type it will conform to when instantiated. This makes it not a whole lot clearer, so let’s run through an example.

For a job board we want to fetch all active vacancies. We can in this case create a VacancyService  class:

Here you see the self-type in action. The VacancyService  defines itself as ‘repository of type VacancyRepository ‘, which implements the findActiveVacancies  method.

this  can be replaced by self  or another word you choose, which is something I like to make the code in VacancyService  somewhat cleaner:

However, there is nothing here that shows that VacancyService  really is of type VacancyRepository . When you want to use this class, you have to mix in the VacancyRepository  behavior yourself:



Back to Dependency Injection

But as you saw in these last to code examples, we injected the necessary VacancyRepository  implementation into the VacancyService .

Let us now complete the exmaple, with a mock repository. First we define the VacancyRepository  with a mock implementation (you could add a JPA implementation yourself):

The Vacancy  is defined as:

Now let’s create a VacancyService  with a MockVacancyRepository . As a matter of fact, because VacancyRepository  is abstract, we have to chose a specific implementation ( MockVacancyRepository) to let the code compile.

As for the word cake, we have now baked a service cake with two slices, the service and the repository.

Let’s conclude this post with a complete Scala worksheet example, that you can paste in in Scala IDE:

Writing this post made a lot of things clearer for me. If you have any additions, or want to show me where I am wrong, feel free to leave a comment.