我有一个特征,其中(除其他外)我想要一个方法来创建类的新实例,然后还有其他方法使用该类的实例。
我的代码的一个非常精简的版本是:
trait A {
def prev: A
def get(end: A): A
}
class B extends A {
def prev: B = new B()
def get(end: B): B = end.prev
}
我想在这里展示的是 next 将返回该类的一个新实例(实际上带有一些新的构造函数参数)并且 get 方法将在内部使用 next (以及其他逻辑)
上面的问题是编译器说“B类必须实现抽象成员get(end:A):A”,这是合理的。
我尝试使用类型边界来解决它:
trait A {
def prev: A
def get(end: A): A
}
case class B extends A {
def prev[TX <: A]: TX = new B()
def get[TX <: A](end: TX): TX = end.prev
}
但现在错误是“B 类型的表达式不符合预期的 TX 类型”new B()
和“A 类型的表达式不符合预期的 TX 类型”end.prev
我不明白为什么这是一个问题,因为接下来要返回一个 B,它是 A 的子类型,这就是 TX。
有没有办法实现我希望在这里做的事情?
一点上下文,以防以上所有内容看起来都太抽象了。我正在实现一个循环双向链表,因为我找不到类似的东西。特征包括:
trait Circular[T] {
// Nodes in the list from the current position up to but NOT INCLUDING the end
def toStream(end: Circular[T]): Stream[Circular[T]]
def prev: Circular[T]
...
我的课看起来像:
case class Node[T](val data: T, var prev: Node[T], var next: Node[T])
case class CircularList[T](first: Node[T], last: Node[T], current: Node[T])
extends Circular[T] {
// Nodes in the list from the current position up to but not including the end
def toStream(end: CircularList[T]): Stream[CircularList[T]] = {
@tailrec
def toStreamRec(end: CircularList[T], acc: Stream[CircularList[T]]): Stream[CircularList[T]] = {
if (this == end) {
acc
} else {
toStreamRec(end.prev, Stream.cons(end.prev, acc))
}
}
toStreamRec(end, Stream.empty)
}
def prev: CircularList[T] = new CircularList[T](first, last, current.prev)
...
所以toStream
映射到get
我的缩减示例中。