在方法中未识别属性类型参数



我有一个我面临的问题的模拟示例。


class Baz[-A](
) {
def p: Unit = println("hi")
}
def n[A](b: Baz[A]): Unit = b.p
trait Foo[R[_] <: Baz[_]] {
def m[A](req: R[A]): Unit = {
n(req)
}
}

我得到这个编译时错误

no type parameters for method n: (b: Baz[A])Unit exist so that it can be applied to arguments (R[A])
--- because ---
argument expression's type is not compatible with formal parameter type;
found   : R[A]
required: Baz[?A]
n(req)

我本来以为这是因为我已经将R[_]的超类型指定为Baz[_],将类型为R[_]的值传递给需要Baz[A]的方法会解析,但编译器似乎不这么认为。我在这里不理解什么?

问题是R[_] <: Baz[_]并不是你认为的那样
这只是暗示应该有一个类RBaz的子类,这不同于对任何类型的xR[x]Baz[x]的子类;这就是你想要的。

值得庆幸的是,该语言确实以一种非常相似的方式提供了一种暗示:R[x] <: Baz[x]解决了问题。


您可以在此处看到运行的代码

相关内容

最新更新