相关疑难解决方法(0)

收集问题中的Scala自我类型和this.type

我试图在scala中围绕抽象和显式自我类型.让我们考虑这个例子:我想为可扩展树创建一个简单的基础:

trait Tree {
  def children: Iterable[Tree]
  def descendants: Iterable[Tree] = { val dv = children.view; dv ++ (dv.flatMap { _.children }) }
}
Run Code Online (Sandbox Code Playgroud)

但是,我希望能够使用某些方法扩展树节点并使用以下方法: 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 })
    }
}
Run Code Online (Sandbox Code Playgroud)

工作变体非常笨拙.

B.摘要类型:失败

trait Tree {
    type Node …
Run Code Online (Sandbox Code Playgroud)

scala self-type abstract-type

9
推荐指数
2
解决办法
414
查看次数

标签 统计

abstract-type ×1

scala ×1

self-type ×1