Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do implicits which are defined in a separate trait after the usage result in a compile error?

Tags:

scala

sbt

Why does the following code results into a compile error:

class MyImplicit

class FooTest extends ImplicitProvider {

  def getImplicit(implicit i: MyImplicit) = i

  getImplicit
}

trait ImplicitProvider {
  implicit val myImplicit = new MyImplicit
}

The compile error is:

could not find implicit value for parameter i: MyImplicit getImplicit

If I move the trait ImplicitProvider above the class FooTest everything works fine.

I compile with scala 2.11.7 and sbt 0.13.9.

Is this expected behaviour or a bug?

like image 407
regexp Avatar asked Feb 18 '16 11:02

regexp


People also ask

What is the use of Implicits in Scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.

Where does Scala search for Implicits?

Companion Objects of a Type The method sorted takes an implicit Ordering . In this case, it looks inside the object Ordering , companion to the class Ordering , and finds an implicit Ordering[Int] there.

What is an implicit parameter in Java?

The implicit parameter in Java is the object that the method belongs to. It's passed by specifying the reference or variable of the object before the name of the method. An implicit parameter is opposite to an explicit parameter, which is passed when specifying the parameter in the parenthesis of a method call.

How do you use traits in Scala?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.


1 Answers

This appears to be a "feature". Take a look at the comments in this ticket.

Apparently this is expected behaviour when the type of the implicit is not explicitly specified. So you can fix it by adding a type annotation to the implicit val.

class MyImplicit

class FooTest extends ImplicitProvider {

  def getImplicit(implicit i: MyImplicit) = i

  getImplicit
}

trait ImplicitProvider {
  implicit val myImplicit: MyImplicit = new MyImplicit
}
like image 100
Jasper-M Avatar answered Nov 15 '22 05:11

Jasper-M