Search code examples
scalaself-typecake-pattern

Cake pattern, self: UserRepositoryComponent =>


I'm trying to understand the cake pattern.

I found this gist: https://gist.github.com/2127745

But I don't understand this syntax:

// Explicit dependency on User Repository
self: UserRepositoryComponent =>

Can someone explain it please?


Solution

  • That's what's known as a self-type annotation. It means that you can assume that the object for the class has the declared type (in this case UserRepositoryComponent, or some subtype), and also (as a bonus) lets you refer to the "this" object at that level as "self", or whatever other name you specify. The self-type annotation is subtly powerful. It expresses a requirement for any implementation of the class (an earlier version of Scala expressed that syntactically as "requires UserRepositoryComponent") but doesn't actually imply a publicly visible type constraint (which would happen if you had said "extends UserRepositoryComponent"). The implementation requirement is enforced at any instantiation of the annotated class, but nowhere else. Self-type annotations are key to the "cake pattern", an encoding of program modules as Scala objects.