除了子类型

时间:2017-12-10 00:09:34

标签: scala functional-dependencies implicits

如果您运行下面的代码,则会出现ambiguous implicit错误:

class Foo[T,I](val msg: I)
object Foo {
  implicit def provide[T]: Foo[T,String] =
    new Foo("I came from a place you can't touch so subtyping can't help you")
}

class User
object User {
  implicit object userFoo extends Foo[User,Int](42)
}

def fooOf[T,I](U: T)(implicit foo: Foo[T,I]): Foo[T, I] = foo

fooOf(new User).msg //epic fail:
//Error:(232, 7) ambiguous implicit values:
//both object userFoo in object User of type A$A153.this.User.userFoo.type
//and method provide in object Foo of type [T]=> A$A153.this.Foo[T,String]
//match expected type A$A153.this.Foo[A$A153.this.User,I]
//fooOf(new User).msg;//
//^

通常,Scala会将T中的F[T,I]类型的伴随对象优先于F[_]&#39}。但不是在这种情况下,因为两个定义位置中的I类型不同(如果它们都是String,Scala会选择Foo[User,String] Companion对象中的User < / p>

我无法(或者更好地说不想)触摸Foo随播广告对象来实施LowerPriorityImplicits子类型技术,并在其中定义F[User,I]个实例更高的优先级。我还能做什么?

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,允许函数Restaurant仅显式查看伴随对象:

fooOf

我发现它后立即发布。不知道它为增益带来了多少麻烦。

相关问题