【问题标题】:Scala ambiguous reference to overloaded definition with two implicit parametersScala 对带有两个隐式参数的重载定义的模糊引用
【发布时间】:2013-06-28 14:02:24
【问题描述】:

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 

【问题讨论】:

    标签: scala overloading implicit erasure


    【解决方案1】:

    总之

    trait Foo; trait Bar
    
    object Test {
      def apply(implicit foo: Foo) {}
      def apply(implicit bar: Bar) {}
    }
    
    Test.apply   // ambiguous
    

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      相关资源
      最近更新 更多