[英]Trait Type Parameter Not Recognised In Method
I have this mock example of a problem I am facing.我有这个我面临的问题的模拟示例。
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)
}
}
I get this compile time error我得到这个编译时错误
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)
I was expecting that because I have specified the super type for R[_]
to be Baz[_]
passing a value of type R[_]
to a method that requires a Baz[A]
would resolve but the compiler doesn't seem to think so.我期待因为我已将
R[_]
的超类型指定为Baz[_]
将类型R[_]
的值传递给需要Baz[A]
的方法会解析,但编译器似乎没有这么想。 What am I not understanding here?我在这里不明白什么?
The problem is that R[_] <: Baz[_]
doesn't mean what you think it does.问题是
R[_] <: Baz[_]
并不意味着你认为它的意思。
It just implies that there should be a class R
that is a subclass of Baz
, which is different from saying that R[x]
is a subtype of Baz[x]
for any type x
;它只是暗示应该有一个 class
R
是Baz
的子类,这不同于说R[x]
是任何类型x
的Baz[x]
的子类型; which is what you want.这就是你想要的。
Thankfully, the language does provide a way to imply that, in a very similar way: R[x] <: Baz[x]
that fixes the problem.值得庆幸的是,该语言确实提供了一种暗示方式,以非常相似的方式:
R[x] <: Baz[x]
解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.