What is the cake pattern in Scala?
Answer
The cake pattern is a Scala dependency injection technique using traits and self-types, without a DI framework. Each component is defined as a trait with a self-type annotation declaring its dependencies: trait UserRepositoryComponent { val userRepository: UserRepository; trait UserRepository { def find(id: Long): Option[User] } }. Service component: trait UserServiceComponent { self: UserRepositoryComponent =>; val userService: UserService; class UserService { def getUser(id: Long) = userRepository.find(id) } }. Wire everything: object App extends UserServiceComponent with UserRepositoryComponent { val userRepository = new ProductionUserRepository; val userService = new UserService }. Benefits: type-safe DI without reflection; dependencies explicit in types; testable by substituting trait implementations. Downsides: verbose; complex wiring for large applications. Modern Scala projects often use MacWire (compile-time DI) or ZIO ZLayer for dependency injection instead of the cake pattern.
Previous
What is the difference between abstract class and trait in Scala?
Next
What are Scala macros and when are they used?
More Scala Questions
View all →- Intermediate What is the type class pattern in Scala?
- Intermediate What is Akka and what is the actor model?
- Intermediate What is Apache Spark and how does Scala relate to it?
- Intermediate What is Scala's approach to concurrency with Futures and Promises?
- Intermediate What are Scala's monads and how do they work?