Scala 类型不匹配错误尝试将参数化或抽象类型构造函数视为其上限
精简示例:
trait WithUpperBounds[AA[_] <: Set[_], Node, Edge] {
val nodes: AA[Node]
val edges: AA[Edge]
}
class WithoutUpperBounds[AA[_] <: Set[_], Node, Edge](
val nodes: AA[Node],
val edges: AA[Edge]
) extends WithUpperBounds[AA, Node, Edge] {
val nodes2Set: Set[Node] = nodes
val edges2Set: Set[Edge] = edges
}
REPL 输出:
scala> :l …/Sandbox.scala
Loading …/Sandbox.scala...
defined trait WithUpperBounds
<console>:10: error: type mismatch;
found : AA[Node]
required: Set[Node]
val nodes2Set: Set[Node] = nodes
^
<console>:11: error: type mismatch;
found : AA[Edge]
required: Set[Edge]
val edges2Set: Set[Edge] = edges
^
高阶函数,特别是对于理解,使我的问题更加复杂。
Stripped down example:
trait WithUpperBounds[AA[_] <: Set[_], Node, Edge] {
val nodes: AA[Node]
val edges: AA[Edge]
}
class WithoutUpperBounds[AA[_] <: Set[_], Node, Edge](
val nodes: AA[Node],
val edges: AA[Edge]
) extends WithUpperBounds[AA, Node, Edge] {
val nodes2Set: Set[Node] = nodes
val edges2Set: Set[Edge] = edges
}
REPL output:
scala> :l …/Sandbox.scala
Loading …/Sandbox.scala...
defined trait WithUpperBounds
<console>:10: error: type mismatch;
found : AA[Node]
required: Set[Node]
val nodes2Set: Set[Node] = nodes
^
<console>:11: error: type mismatch;
found : AA[Edge]
required: Set[Edge]
val edges2Set: Set[Edge] = edges
^
Higher-order functions especially for comprehensions compound my issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 Seq[_] 描述中的通配符更改为:
Change the wildcard in the Seq[_] description to this:
@thoredge 为我指明了正确的方向。我在 Predef.scala 中找到了解决方案:
通配符会丢弃类型等效性,但您可以抽象任何任意参数而不声明它。我的特质现在看起来像:
@thoredge pointed me in the right direction. I found the solution in Predef.scala:
Wildcards throws away type equivalence but you can instead abstract over any arbitrary parameter without declaring it. My trait now looks like: