Reputation: 2345
In a scala class, a class DogService
with an implicit constructor parameter DogDAO
can be instantiated with any implicit variable name that has the same type.
Ex.
class DogService(implicit val dogDAO: DogDAO)
implicit val dDAO = new DogDAO
val dogService = new DogService // works
Can you pass an implicit variable to a trait without using the same variable name?
Ex.
trait DogService { implicit def myDAO: DogDAO}
implicit val dogDAO = new DogDAO
class AllService(implicit val dogDAO: DogDAO)
val dogService = new AllService with DogService // myDAO is not defined
Upvotes: 1
Views: 1610
Reputation: 128081
When you have defined a class with implicit val
member you also have defined a constructor with an implicit parameter, and that's why your first example works.
It is a completely different thing with a trait, however. Traits cannot have constructor parameters, and you in fact have defined a regular implicit method. This method have to be overridden in the implementing class unless that class is abstract. The reason why it works if you "use the same variable name" is because val
declaration in class constructor arguments automatically generates corresponding item in the class, which does override the trait method.
So, in short, there is no such thing as "passing an implicit variable to a trait" in a sense you mean, and you cannot do what you want.
Upvotes: 2