Scala对带有两个隐式参数的重载定义的含糊不清的引用 [英] Scala ambiguous reference to overloaded definition with two implicit parameters

查看:202
本文介绍了Scala对带有两个隐式参数的重载定义的含糊不清的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

惰性val productService = BeanLookup [ProductDataService]

lazy 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抱怨:

 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 

推荐答案

简而言之

trait Foo; trait Bar

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

Test.apply   // ambiguous

Scala不能通过确定两个隐式变量中只有一个可用来解决重载.

Scala doesn't resolve overloading by figuring out if only one of the two implicits is available.

如果您想在这种情况下重载,则应使用磁铁模式

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"

这篇关于Scala对带有两个隐式参数的重载定义的含糊不清的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆