Scala implicit parameters with default values ​​specified in the companion object

According to Scala Spec (2.8), for an implicit search, it must be defined in a local scope, inherited scope, or in a companion object. Given that it seems to me that the following code should work without explicitly importing the contents of the companion object. I see that this is used in the source of the Scala library (e.g. CanBuildFrom). It also seems that I would have to call XX.foo () from outside the XX class definition and have my implicit parameter from the companion class used. What am I missing?

object XX { implicit def XYZ[T]: (T) => Unit = null } class XX { // import XX._ // Works with this line uncommented... def foo(s: String)(implicit f: (String) => Unit): Unit = { if (f == null) println("Just: " + s) else f(s) } def bar { foo("abc"){ s => println("Func: " + s)} foo("xyz") // <-- Compile error here: could not find implicit value for parameter f } } 
+7
source share
1 answer

I have always interpreted the specification as meaning that the implicit can be defined in the companion object of the implicit parameter, and not in the class containing the definition. Something like that:

 object ZZ { implicit val xyz: ZZ = new ZZ() } class ZZ { def bar: (String) => Unit = null } class XX { def foo(s: String)(implicit f: ZZ): Unit = { if (f.bar == null) println("Just: " + s) else f.bar(s) } def bar { foo("xyz") } } 

As can be seen from section 7.2 of the specification:

The actual arguments that are allowed to pass an implicit parameter of type T fall into two categories. Firstly, all identifiers x that can be obtained at the point of method invocation without prior identification and which indicate an implicit definition (§7.1) or an implicit parameter are suitable. a suitable identifier, therefore, is the local name or member of the attached template, or it can be made available without prior (§4.7). If there are no suitable identifiers according to this rule, then, secondly, the right to participate is also implicit members of some object that belongs to the implicit volume type of implicit parameters, T.

Can you quote the part that indicates the companion object of the containing definition class?

+9
source

All Articles