Here is a simplification of what I encountered. This compiles:
trait A { implicit val x = 1 }
trait B extends A { val y = implicitly[Int] }
While this don't (could not find implicit value):
trait B extends A { val y = implicitly[Int] }
trait A { implicit val x = 1 }
I tried to make my intentions clear by specifying a self-type: trait A { this: B => ... }
, but to no avail.
How do I deal with this kind of dependencies without worrying about how my code is laid out?
Explicit variable declaration means that the type of the variable is declared before or when the variable is set. Implicit variable declaration means the type of the variable is assumed by the operators, but any data can be put in it.
If a name appears in a program and is not explicitly declared, it is implicitly declared. The scope of an implicit declaration is determined as if the name were declared in a DECLARE statement immediately following the PROCEDURE statement of the external procedure in which the name is used.
1. Explicit declarations: a statement in a program that lists variable names and specifies their types 2. Implicit declarations: means of associating variables with types through default conventions.
An explicit declaration is the appearance of an identifier (a name) in a DECLARE statement, as a label prefix, or in a parameter list. A name is explicitly declared if it appears as follows: In a DECLARE statement. The DECLARE statement explicitly declares attributes of names. As an entry constant.
You need to declare the type explicitly, at least for the latter one
trait B extends A { val y = implicitly[Int] }
trait A { implicit val x : Int = 1 }
The rules for implicit visibility is different whether its type is declared explicitely or not. If it is not, the implicit is available (as an implicit) only after the point of declaration.
The reason is that type inference may become too difficult if the type was not declared (as in recursive routine). In many cases, inference would be easy (as in your code) but the spec has to be clear cut.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With