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?
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.
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.
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.
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.
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
}
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