类型参数 [W] 不符合 trait 类型参数边界 [英] type arguments [W] do not conform to trait type parameter bounds

查看:46
本文介绍了类型参数 [W] 不符合 trait 类型参数边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

trait SomeClass {...}trait AnotherClass[+V <: SomeClass] {...}trait SomeAnotherClass[+V <: SomeClass] {protected def someFunc[W >: V](anotherClass: AnotherClass[W]) = {...}}

我收到此错误:

类型参数 [W] 不符合 trait AnotherClass 的类型参数边界 [+V <: SomeClass][错误] protected def someFunc[W >: V](anotherClass: AnotherClass[W]) = ...[错误]^[错误] 发现一个错误

当我执行 [W >: V <: SomeClass] 而不是 [W >: V] 时,我不会出错,但是在在这种情况下,它隐藏了变量.请帮忙,如何解决这个问题.

更新:

protected def someFunc(anotherClass: AnotherClass[V]) = {...}

我得到错误协变类型V出现在类型的逆变位置

解决方案

当你说 W >: V 时,你是说类型参数 WsomeFunc 必须具有 V 的下限类型.这意味着 W 可以是 V 或其任何超类型,这将打破 V <: SomeClass 的类型界限.

例如 Any >: SomeClass,所以在这种假设情况下 W 可能是 Any,但是 Any = V <: SomeClass 也不是真的,所以类型边界被打破了.

当你说 W >: V <: SomeClass 时,W 有一个 V下界em> 和 SomeClass上限.WSomeClass 的上界很重要,因为AnotherClass 的包含类型也有SomeClass 的上界>.没有它,它会尝试允许 AnotherClass[Any](或其他一些不是 SomeClass 的超类型),当然它不能.>

你如何解决这个问题?你让你选择一种方法来做到这一点.您不能同时拥有 W >: VAnotherClass[+V <: SomeClass].这是行不通的,因为类型边界冲突.

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

解决方案

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.

这篇关于类型参数 [W] 不符合 trait 类型参数边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆