现在,我正在尝试使用以下代码实现链接列表的变体,但我遇到了麻烦。基本上,我正在尝试创建不同类型的节点,这些节点将通过下一个方法相互连接。因此,我有两个类,NodeA[T]
和NodeB[T]
,它们继承自抽象类NodeTrait[T]
。我只想要下一个是NodeTrait[T]
子类型的任何类型,并包含在Option
中。因此,我希望其次是Option[NodeA[T]]
或Option[NodeB[T]]
类型。
但是,我收到一个编译错误,说Option[NodeTrait[T]]
类型的表达式没有确认预期类型NodeTrait[T]
。我不确定如何解决这个问题。我正在考虑使用协方差并将NodeTrait[T]
更改为NodeTrait[+T]
,但我仍然会收到更多编译错误。有没有人有解决这个问题的技巧?
abstract class NodeTrait[T](x:T) {
var next:Option[NodeTrait[T]]
def insert(y: T):Option[NodeTrait[T]]
}
class NodeA[T](x:T) extends NodeTrait[T](x){
def insert(y: T): NodeTrait[T] = {
val newnode = new NodeA[T](y)
next = Some(new NodeA[T](y))
next
}
next = None
}
class NodeB[T](x:T) extends NodeTrait[T](x){
def insert(y: T): NodeTrait[T] = {
val newnode = new NodeB[T](y)
next = Some(new NodeB[T](y))
next
}
next = None
}
答案 0 :(得分:3)
我不知道你的代码做了什么,让我们假设它只是简化抽象版本的东西,但这里编辑的代码编译:
abstract class NodeTrait[T](x:T) {
var next:Option[NodeTrait[T]]
def insert(y: T):Option[NodeTrait[T]]
}
class NodeA[T](x:T) extends NodeTrait[T](x){
def insert(y: T): Option[NodeTrait[T]] = {
val newnode = new NodeA[T](y)
next = Some(new NodeA[T](y))
next
}
var next: Option[NodeTrait[T]] = None
}
class NodeB[T](x:T) extends NodeTrait[T](x){
def insert(y: T): Option[NodeTrait[T]] = {
val newnode = new NodeB[T](y)
next = Some(new NodeB[T](y))
next
}
var next: Option[NodeTrait[T]] = None
}
您在NodeB和NodeA insert
方法中指定了不同的(来自NodeTrait)返回类型。