斯卡拉使用隐式自我类型
问题描述:
我有一个隐式类需要用户数据库。我想在隐式类中使用自我类型,因此我可以将测试范围内的数据库实现切换到模拟版本。在这种情况下,我如何混合数据库提供者?例如,我希望RuchUser的用户不用担心必须通过提供默认混音来混合UserDatabaseProvider。因此,用户可以只做User("name").userContext
,并在测试范围内执行相同的操作,我将提供默认混合使用模拟数据库提供程序?斯卡拉使用隐式自我类型
case class User(name: String)
object User {
implicit class RichUser(self: User) { this: UserDatabaseProvider =>
def userContext: String = this.getUserContext(self.name)
}
}
// Usage of Rich user should be below as I want to provide already mixed-in implicit
import User._
val context = User("name").uerContext
答
我觉得你太过于复杂了。
case class User(name: String) {
def context()(implicit db: UserDatabaseProvider): UserContext = {
db.getUserContext(name)
}
}
我会去进一步建议蛋糕模式可能比使用implicits更适用。
class UserService extends UserDatabaseProvider {
def context(user: User): UserContext = getUserContext(user.name)
}
class TestUserService extends UserService with TestDatabase
让“斯卡拉最右边的胜利”钻石分辨率为您完成这项工作。