简体   繁体   English

类型构造函数的Scala继承

[英]Scala Inheritance of Type Constructor

Right now, I am trying to implement a variant of a Linked List with the following code, but I am having trouble with it. 现在,我正在尝试使用以下代码实现链表的变体,但是我遇到了麻烦。 Basically, I am trying to create different type of nodes that will connect with each other by the next method. 基本上,我正在尝试创建不同类型的节点,这些节点将通过下一个方法相互连接。 Thus, I have two classes, NodeA[T] and NodeB[T] , that inherited from the abstract class, NodeTrait[T] . 因此,我有两个类NodeA[T]NodeB[T] ,它们从抽象类NodeTrait[T]继承。 I just want next to be any type that is a subtype of NodeTrait[T] and is contained in Option . 接下来,我只想成为NodeTrait[T]的子类型并包含在Option任何类型。 Thus, I want next to be either the type Option[NodeA[T]] or Option[NodeB[T]] . 因此,我接下来要Option[NodeA[T]]Option[NodeB[T]]

However, I get a compiler error saying expression of type Option[NodeTrait[T]] doesn't confirm to expected type NodeTrait[T] . 但是,我收到一个编译器错误,提示类型Option[NodeTrait[T]]表达式未确认为期望的NodeTrait[T]类型。 I am not exactly sure how to solve this problem. 我不确定如何解决这个问题。 I was thinking about using covariance and change NodeTrait[T] to NodeTrait[+T] but I still get more compiling errors. 我当时正在考虑使用协方差并将NodeTrait[T]更改为NodeTrait[+T]但仍然遇到更多编译错误。 Does anybody have any tips to solve this issue? 有人有解决此问题的提示吗?

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



}

I don't know what your code do, lets assume it's just simplified abstract version of something, but here edited code that compiles: 我不知道您的代码做什么,让我们假设它只是某些东西的简化抽象版本,但是这里编辑的代码可以编译:

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
}

You specified different (from NodeTrait) return types in you NodeB and NodeA insert method. 您在NodeB和NodeA insert方法中指定了不同的(不同于NodeTrait)返回类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM