简体   繁体   中英

Implicit conversion of a generic container for an implicit parameter in Scala

Is there a way to make this work? (Scala 2.8.1)

class A
def f(implicit a: A) = 0

class Vendor[T](val v: T)
implicit val vendor = new Vendor(new A)
implicit def vendorToVal[T](implicit v: Vendor[T]) = v.v
f

The error is: 'diverging implicit expansion for type A starting with method vendorToVal'

This is related to Lift 2.2 dependency injection, the real code looks like this:

class UserStore(implicit db: DbAccess)
object DependencyFactory extends Factory {
  implicit val db = new FactoryMaker[DbAccess](Model) {}
  import db._ // implicit conversion would allow to remove this import

  implicit val userStore = new FactoryMaker[UserStore](new UserStore) {}
}

This question is related to: Is there a way to implicitly convert an implicit parameter in Scala?

The problem is caused with vendorToVal method - I observed the same behavior many times, when I've been using implicit parameters in implicit type-parametrized methods. Unfortunately, I've found no simple and elegant glue in 2.8._.

Some interesting threads, related to the topic:

  1. http://scala-programming-language.1934581.n4.nabble.com/scala-Why-is-this-a-diverging-implicit-td1998156.html
  2. http://www.scala-lang.org/node/6847

In Scala 2.9 trunk, you can do this:

scala> class A
defined class A

scala> def f(implicit a: A) = 0
f: (implicit a: A)Int

scala> 

scala> class Vendor[T](val v: T)
defined class Vendor

scala> implicit def value[T: Vendor] = implicitly[Vendor[T]].v
value: [T](implicit evidence$1: Vendor[T])T

scala> implicit val vendor = new Vendor(new A)
vendor: Vendor[A] = Vendor@bbb2d0

scala> f
res0: Int = 0

Calling f will search for a value of type A , and find the implicit value[A] , which requires an evidence parameter of type Vendor[A] . It resolves this evidence parameter to vendor .

I don't think implicits were that powerful in 2.8.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM