2013-04-30 41 views
4

我要定义一些特质,描述不同的树节点如下:为什么在类型成员中使用traits在subtrait中给出“错误:类型不匹配”?

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) 
    } 
} 

能否请你解释一下,为什么这个代码不编译?哪里不对?

回答

4

HasParent中定义的类型P是一种抽象类型。这意味着每个HasParent可以有另一种类型P,只要它满足(上)类型边界。

当你调用setParent一些HasParentT,你有没有保证this具有所需类型的特定HasParent的。

你确定你不想写:

type P = Node with HasChildren 
+0

感谢。它现在编译。 Intllij IDEA仍将此代码突出显示为错误:)但是,我如何用某些其他特性(如HasSomeSpecialChildren)重写P? – chardex 2013-04-30 21:45:06

+0

您不能重写具体类型成员。无论如何,如果你改变'P',当你调用'add'时,你必须确保'HasChildren'中的'this'引用具有正确的类型...可能使用子类型和a在'HasParent'上输入参数。 – gzm0 2013-04-30 22:03:56

+0

谢谢。子类型是什么意思?对不起,我是斯卡拉新手。你能为我的情况提供正确的例子吗? – chardex 2013-05-01 14:51:10

相关问题