2013-06-28 59 views
1

懶惰VAL productService = BeanLookup [ProductDataService]Scala的曖昧參照重載定義具有兩個隱式參數

object BeanLookup { 

    def apply[T](implicit manifest: Manifest[T], context: ActorContext) = { 
    val beanLookup = 
     context.actorFor("/user/spring/beanLookup") 
    Await.result(
     (beanLookup.ask(LookupBean(manifest.erasure))(timeout)).mapTo[T](manifest), 
     timeout.duration) } 

    def apply[T](implicit manifest: Manifest[T], system: ActorSystem) = { 
    val beanLookup = 
     system.actorFor("/user/spring/beanLookup") 
    Await.result(
     (beanLookup.ask(LookupBean(manifest.erasure))(timeout)).mapTo[T](manifest), 
     timeout.duration) } } 

scalac抱怨:

scala: ambiguous reference to overloaded definition, 
both method apply in object BeanLookup of type (implicit manifest: Manifest[com.tooe.core.service.LocationCategoryDataService], implicit system: akka.actor.ActorSystem)com.tooe.core.service.LocationCategoryDataService 
and method apply in object BeanLookup of type (implicit manifest: Manifest[com.tooe.core.service.LocationCategoryDataService], implicit context: akka.actor.ActorContext)com.tooe.core.service.LocationCategoryDataService 

回答

9

總之

trait Foo; trait Bar 

object Test { 
    def apply(implicit foo: Foo) {} 
    def apply(implicit bar: Bar) {} 
} 

Test.apply // ambiguous 

如果只有兩個implicits中的一個可用,Scala不解決重載問題。如果你想在這種情況下重載,你應該使用magnet pattern

object FooOrBar { 
    implicit def fromFoo(implicit f: Foo) = FooOrBar(Left(f)) 
    implicit def fromBar(implicit b: Bar) = FooOrBar(Right(b)) 
} 
case class FooOrBar(e: Either[Foo, Bar]) 

object Test { 
    def apply(implicit i: FooOrBar) = i.e match { 
    case Left (f) => "foo" 
    case Right(b) => "bar" 
    } 
} 

Test.apply // could not find implicit value for parameter i: FooOrBar 

implicit val f = new Foo {} 
Test.apply // "foo"