Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicits and order of declaration

Tags:

scala

implicit

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?

like image 699
elbowich Avatar asked Mar 07 '12 11:03

elbowich


People also ask

What is difference between implicit and explicit declaration?

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.

What does it mean by implicit declaration?

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.

What is implicit and explicit declaration in C?

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.

What is meant by explicit variable declaration?

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.


1 Answers

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.

like image 86
Didier Dupont Avatar answered Sep 21 '22 23:09

Didier Dupont