I have started learning scala for a while now and now looking at cake pattern. I got the example from here
trait UserRepositoryComponent {
def userLocator: UserLocator
trait UserLocator {
def findAll: List[User]
}
}
trait UserRepositoryJPAComponent extends UserRepositoryComponent {
val em: EntityManager
def userLocator = new UserLocatorJPA(em)
class UserLocatorJPA(val em: EntityManager) extends UserLocator {
def findAll = {
println("Executing a JPA query")
List(new User, new User)
}
}
}
trait UserServiceComponent {
def userService: UserService
trait UserService {
def findAll: List[User]
}
}
trait DefaultUserServiceComponent extends UserServiceComponent {
this: UserRepositoryComponent =>
def userService = new DefaultUserService
class DefaultUserService extends UserService {
def findAll = userLocator.findAll
}
}
To me it looks like too many boilerplate code to get the JPA repository injected to service.
However this code would do the same with much lesser number of lines
trait UserRepository {
def findAll
}
trait JPAUserRepository extends UserRepository {
val em: EntityManager
def findAll = {
em.createQuery
println("find using JPA")
}
}
trait MyService {
def findAll
}
trait MyDefaultService extends MyService {
this: UserRepository=>
}
Instantiating both scenarios.
val t1 = new DefaultUserServiceComponent with UserRepositoryJPAComponent {
val em = new EntityManager()
}
t1.userService.findAll
val t2 = new MyDefaultService with JPAUserRepository {
val em = new EntityManager
}
t2.findAll
Second scenario uses much less code, and uses DI. Can you help me understand what extra advantages cake pattern brings.