简体   繁体   English

Scala对带有两个隐式参数的重载定义的不明确引用

[英]Scala ambiguous reference to overloaded definition with two implicit parameters

lazy val productService = BeanLookup[ProductDataService] 惰性val productService = BeanLookup [ProductDataService]

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 complains : 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 

In short 简而言之

trait Foo; trait Bar

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

Test.apply   // ambiguous

Scala doesn't resolve overloading by figuring out if only one of the two implicits is available. Scala无法通过找出两个隐式变量中只有一个可用的方法来解决重载问题。

You should use the magnet pattern if you want overloading in such a case. 如果您想在这种情况下过载,则应使用磁铁图案

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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