Implications and declaration procedure

Here is a simplification of what I came across. This compiles:

trait A { implicit val x = 1 } trait B extends A { val y = implicitly[Int] } 

While this is not (could not find an 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 self-type: trait A { this: B => ... } , but to no avail.

How can I deal with such dependencies without worrying about how my code is laid out?

+6
source share
1 answer

You need to explicitly declare the type, at least for the latter

 trait B extends A { val y = implicitly[Int] } trait A { implicit val x : Int = 1 } 

Implicit visibility rules differ, whether explicitly declared or not. If this is not the case, implicit is available (as implicit) only after the declaration point.

The reason is that type inference can become too complicated if the type has not been declared (as in a recursive routine). In many cases, the conclusion would be simple (as in your code), but the specification should be clear.

+11
source

Source: https://habr.com/ru/post/910163/


All Articles