I'm trying to follow the example from this blog. I understand the example but having trouble implementing it.
trait Database {
// ...
}
trait UserDb {
this: Database =>
// ...
}
trait EmailService {
this: UserDb =>
// Can only access UserDb methods, cannot touch Database methods
}
The example mentions that the full Database functionality will be hidden from the EmailService - this is what i'm after but don't know how to implement these traits correctly.
This is what i tried to implement:
trait Database {
def find(query: String): String
}
trait UserDb {
this: Database =>
}
trait EmailService {
this: UserDb =>
}
trait MongoDatabase extends Database {
}
trait MongoUserDb extends UserDb with MongoDatabase{
}
class EmailServiceImpl extends EmailService with MongoUserDb {
override def find(query: String): String = {
"result"
}
}
It looks weird to me becasue MongoDatabase trait didn't asked for find
implementation and when i implemented EmailService
i was then prompted for find
implementation,although the example mentioned this will be hidden from the EmailService
. What am i missing here?
After reading your comments, I'm trying to implement what i'm being trying to understand on an example that is closer to what i'm actually trying to do.
The first snippet won't compile, but the second one will...
At the end of the day i want to have different Repository
implementations where i can switch between the Databases they rely on, am i close with one of the snippets below?
trait Database {
def find(s: String): String
}
trait Repository {
this: Database =>
}
class UserRepository extends Repository {
def database = new MongoDB
class MongoDB extends Database {
def find(s: String): String = {
"res"
}
}
}
trait Repository {
def database: Database
trait Database {
def find(s: String): String
}
}
trait UserRepository extends Repository {
def database = new MongoDB
class MongoDB extends Database {
def find(s: String): String = {
"res"
}
}
}