问题
trait SomeClass {
...
}
trait AnotherClass[+V <: SomeClass] {
...
}
trait SomeAnotherClass[+V <: SomeClass] {
protected def someFunc[W >: V](anotherClass: AnotherClass[W]) = {
...
}
}
I'm getting this error:
type arguments [W] do not conform to trait AnotherClass's type parameter bounds [+V <: SomeClass]
[error] protected def someFunc[W >: V](anotherClass: AnotherClass[W]) = ...
[error] ^
[error] one error found
I don't get error when I do [W >: V <: SomeClass]
instead of just [W >: V]
, but in this case, it is shadowing the variable. Please help, how to resolve this.
UPDATE:
protected def someFunc(anotherClass: AnotherClass[V]) = {
...
}
I get error covariant type V occurs in contravariant position in type
回答1:
When you say W >: V
, you're saying that the type parameter W
of someFunc
must have a lower type bound of V
. That means that W
can be V
or any super-type of it, which would break the type bounds that V <: SomeClass
.
For example Any >: SomeClass
, so W
in this hypothetical situation could be Any
, but Any = V <: SomeClass
is not also not true, so the type bounds break.
When you say W >: V <: SomeClass
, then W
has a lower bound of V
and an upper bound of SomeClass
. The upper bound of SomeClass
for W
is important, because the contained type of AnotherClass
also has an upper bound of SomeClass
. Without that, it would try to allow AnotherClass[Any]
(or some other super-type that isn't SomeClass
), which of course it can't.
How can you solve this? You have you pick one way to do it. You can't have W >: V
and AnotherClass[+V <: SomeClass]
at the same time. It just won't work, because the type bounds conflict.
来源:https://stackoverflow.com/questions/28383284/type-arguments-w-do-not-conform-to-trait-type-parameter-bounds