Scala ambiguous reference to overloaded definition with two implicit parameters

北城以北 提交于 2019-12-04 19:14:41

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.

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!