scala – 为什么在类型成员中使用traits会在subtrait中给出“err
发布时间:2020-12-16 10:02:56 所属栏目:安全 来源:网络整理
导读:我想定义一些描述不同树节点的特征,如下所示: trait Node trait HasParent { this: Node = type P : Node with HasChildren def parent: P def setParent(parent: P)}trait HasChildren { this: Node = def children: Seq[Node] protected def add[T : Node
我想定义一些描述不同树节点的特征,如下所示:
trait Node trait HasParent { this: Node => type P <: Node with HasChildren def parent: P def setParent(parent: P) } trait HasChildren { this: Node => def children: Seq[Node] protected def add[T <: Node with HasParent](child: T) { child.setParent(this) // error: type mismatch; // found : HasChildren with Node // required: child.P // child.setParent(this) } } 你能解释一下,为什么这段代码不能编译?怎么了? 解决方法
HasParent中定义的类型P是抽象类型.这意味着每个HasParent可以有另一个类型P,只要它满足(上)类型绑定.
当您使用T在某些HasParent上调用setParent时,您无法保证它具有该特定HasParent的必需类型. 你确定你不想写: type P = Node with HasChildren (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |