我在尝试理解Scala中的抽象和显式自类型。让我们考虑这个例子:我想创建一个可扩展树的基础,如下所示:
然而,我想要扩展树节点并使用这些方法,例如:
为此,我尝试了:
A. this.type: 失败
工作变体相当笨拙。抽象类型:失败。
由我理解,由于路径特定类型不匹配,完全无法工作。
C. 类型参数(泛型):OK
“Works OK,但在派生类中维护不太好。”
“有没有什么想法可以使前两个变量在不编写大量代码的情况下正常工作?”
“同时,使用 this.type 我遇到了实现问题。”
trait Tree {
def children: Iterable[Tree]
def descendants: Iterable[Tree] = { val dv = children.view; dv ++ (dv.flatMap { _.children }) }
}
然而,我想要扩展树节点并使用这些方法,例如:
tree.children foreach { _.newMethod() }
。为此,我尝试了:
A. this.type: 失败
trait Tree {
def children: Iterable[this.type]
def descendants: Iterable[this.type] = {
val dv = children.view
// FAIL: type mismatch; found : scala.collection.IterableView[com.abovobo.data.Tree,Iterable[_]] required: Iterable[Tree.this.type]
// dv ++ (dv.flatMap { _.children })
// OK:
dv.++[this.type, Iterable[this.type]](dv.flatMap[this.type, Iterable[this.type]]{ _.children })
}
}
工作变体相当笨拙。抽象类型:失败。
trait Tree {
type Node <: Tree
def children: Iterable[Node]
def descendants: Iterable[Node] = {
val dv = children.view
// FAIL: type mismatch; found : scala.collection.IterableView[com.abovobo.data.Tree#Node,Iterable[_]] required: Iterable[Tree.this.Node]
dv ++ (dv.flatMap { _.children })
}
}
由我理解,由于路径特定类型不匹配,完全无法工作。
C. 类型参数(泛型):OK
trait Tree[+Node <: Tree[Node]] {
def children: Iterable[Node]
def descendants: Iterable[Node] = {
val dv = children.view
dv ++ (dv.flatMap { _.children })
}
}
“Works OK,但在派生类中维护不太好。”
“有没有什么想法可以使前两个变量在不编写大量代码的情况下正常工作?”
“同时,使用 this.type 我遇到了实现问题。”
trait BiDTree extends Tree {
def parent: Option[this.type]
}
// how to accept this param? Option[TreeImpl] doesn't work.
class TreeImpl(val parent: Option[???]) extends BiDTree {
// ...
}
谢谢!
c.incr().decr()
示例),但对于集合来说则不行。 - tuxSlayer