为什么每个人都使用这种形式的定义:
trait UserServiceComponent {
def userService: UserService
trait UserService {
def findAll: List[User]
def save(user: User)
}
}
取而代之的是:
trait UserService {
def findAll: List[User]
def save(user: User)
}
trait UserServiceComponent {
def userService: UserService
}
第二种方法似乎更通用,因为 UserService 特征未绑定到特定的组件实例。
有什么我想念的吗?
编辑:通过“更通用”,我的意思是你可以做这样的事情(将两个具有不同 impl. 的蛋糕混合成一个):
object Program extends App with UserServiceComponent with ProductServiceComponent {
object Cake1 extends UserServiceComponentImpl with DatabaseComponent1Impl {
}
object Cake2 extends ProductServiceComponentImpl with DatabaseComponent2Impl {
}
def userService = Cake1.userService
def productService = Cake2.productService
}
// def
trait DatabaseComponent{
}
trait UserService {
}
trait UserServiceComponent {
def userService: UserService
}
trait ProductService {
}
trait ProductServiceComponent {
def productService: ProductService
}
// impl
trait DatabaseComponent1Impl extends DatabaseComponent {
}
trait DatabaseComponent2Impl extends DatabaseComponent {
}
trait UserServiceComponentImpl extends UserServiceComponent {
self:DatabaseComponent =>
def userService = new UserService {}
}
trait ProductServiceComponentImpl extends ProductServiceComponent {
self:DatabaseComponent =>
def productService = new ProductService {}
}
如果您将 UserService 定义为嵌套特征,那么您将得到一个异常:类型不匹配;找到:Program.Cake1.UserService,需要:Program.UserService