有没有一种方法可以在Scala中隐式转换隐式参数? [英] Is there a way to implicitly convert an implicit parameter in Scala?
问题描述
有没有办法使它工作(Scala 2.8.1):
Is there a way to make this work (Scala 2.8.1):
class A
class B
def f(implicit b: B) {}
implicit val a = new A
implicit def aToB(a: A) = new B
f(a) // works ok
f // error: could not find implicit value for parameter b: B
实际上,我的问题是Lift的(2.2)依赖注入,我试图将Vendor [T]转换为T,并隐式地在类构造函数中要求它,而无需在每个val之后添加导入:
Actually my problem is with Lift's (2.2) dependency injection, i'm trying to convert Vendor[T] to T and implicitly require it in a class constructor without adding imports after each val:
object DependencyFactory extends Factory {
implicit def vendorToVal[T](vendor: Vendor[T]): T = vendor.vend
implicit val db = new FactoryMaker[DbAccess](Model) {}
//uncommenting the following line makes it work, but can we avoid it?
//import db._
implicit val userStore = new FactoryMaker[UserStore](new UserStore) {}
}
UserStore
所在的位置:
class UserStore(implicit db: DbAccess)
我做错什么了吗?
更新
感谢轻松天使回答了第一部分.但这并不能解决我的Lift DI问题,因为事实证明范围存在相反的转换(从T到Vendor [T]),并且两者都导致错误:分散隐式扩展".
Thanks to Easy Angel for answering the first part. But it doesn't solve my Lift DI problem because it turns out that there is an opposite conversion in scope (from T to Vendor[T]) and having those both leads to 'error: diverging implicit expansion'.
可以解决吗?
UPDATE2
在上一版本之后又提出了一个问题:将某个Container [T]转换为T,并在范围内包含Container [U]的隐式实例,而具有隐式参数U的函数也会导致发散的隐式扩展": >
Wow one more problem after previous: having a conversion from some Container[T] to T with implicit instance of Container[U] in scope and a function with implicit parameter U leads to 'diverging implicit expansion' too:
class A
case class Vendor[T](v: T)
def f(implicit a: A) {}
implicit val vendor = Vendor(new A)
implicit def vendorToVal[T](implicit v: Vendor[T]) = v.v
f
有任何提示吗?
推荐答案
您几乎做到了.您只需要声明a
隐式:
You almost made it. You only need to declare a
implicit:
implicit def aToB(implicit a: A) = new B
在这种情况下,编译器尝试为f
的第一个隐式参数找到一些隐式的B
,并找到aToB
.超过编译器的关系以满足aToB
的要求(implicit a: A
)并找到您的implicit val a
.
In this case compiler tries to find some implicit B
for the first implicit argument of f
and it finds aToB
. Than compiler ties to satisfy aToB
's requirement (implicit a: A
) and finds your implicit val a
.
这篇关于有没有一种方法可以在Scala中隐式转换隐式参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!