🔴 Scala Intermediate

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.