Question

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?

Was it helpful?

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.

OTHER TIPS

It's a self type annotation, explained for example here. If a self-type is given, it is taken as the type of this inside the trait. It lets Trait RealUserServiceComponent, via the self:UserRepositoryComment declaration say it can only be applied to classes that extend the UserRepositoryComment trait.

This is self-type annotation. It's a specification of what can extend your type. Like 'extends', but in the opopposite direction. Knowing that all your subtypes are some implementations of UserRepositoryComponent gives you some additional bonus. Namely you can call all of its methods as they were your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top