scala – 如何使用无类型约束来特化特征?

首先,如果我的问题不清楚,请告诫我.我还没有完全接受
Scala的说法,所以我可能会混淆术语.不过,我认为我的例子会更清楚.

我正在尝试创建一个特征层次结构,它基本上描述了图形中的顶点 – 任何可以有父列表和子列表的对象.

进一步来说:

> 1)分层可能有也可能没有父母.
> 2)如果是,则父母是分层的.
> 3)Hierarchical将有子级,也是Hierarchical.

这是我的一般特征:

/*
  Hierarchical takes two type parameters: Parent and Child. 
  These should be Hierarchicals with parameters Parent and Child as well.
*/
trait Hierarchical[Parent <: Hierarchical[Parent, Child],
                   Child <: Hierarchical[Parent, Child]] {

  // parents must be passed by constructor lest they are treated as None. 
  // (Requirement 1, 2)
  val parents: Option[List[Hierarchical[Parent, Child]]] = None

  // children can be added, so mutability needed (Requirement 3)
  var children: List[Hierarchical[Parent, Child]] = List()

  def addChild(child: Child) = children ++= List(child)
}

对此的一个特殊化是一个“根”顶点,它的父节点不存在,所以根本不应该指定类型 – 因此,它是None.这是我尝试专门化Hierarchical特征:

/*
  A RootHierarchical has no parents. It does, however, have
  children whose parents are RootHierarchicals and whose children
  are Child.
  A parent can be none (Requirement 1)
*/
trait RootHierarchical[Child <: Hierarchical[RootHierarchical, Child]]
  extends Hierarchical[None.type, Child] {
  override val parents = None
}

IntelliJ对此很满意,但我写的测试不是编译:

import org.scalatest.FlatSpec

class TestHierarchy extends FlatSpec {

  "A Hierarchical object" should "be constructable" in {

    /*
    Create a dummy
     */
    class DummyHierarchical(override val parents: List[DummyParentHierarchical])
      extends Hierarchical[DummyParentHierarchical, DummyHierarchical]

    class DummyParentHierarchical extends RootHierarchical[DummyHierarchical]

    val dummyParent = new DummyParentHierarchical
    val dummyChild = new DummyHierarchical(List(dummyParent))
    dummyParent.addChild(dummyChild)

    assert(dummyParent.parents.isEmpty)
    assert(dummyParent.children.nonEmpty)
  }
}

错误在这里:

Error:(14, 11) type arguments [None.type,Child] do not conform to trait Hierarchical's type parameter bounds [Parent <: Hierarchical[Parent,Child],Child <: Hierarchical[Parent,Child]]
  extends Hierarchical[None.type, Child] {

我的问题是:我怎样才能创建这种专业化?我知道None.type不是Hierarchical类型,但我怎么能专门针对它呢?

最佳答案 在做了一些头脑风暴之后,我发现父母的类型不需要指定 – 它们可以是一些任意的Hierarchical类型,并且将具有默认的Nil.

这是我的实现:

// T is the type of children -- they should be Hierarchicals.
trait Hierarchical[T <: Hierarchical[T]] {
  // The parents will be a list of some arbitrary Hierarchical
  val parents: List[Hierarchical[_]] = Nil
  var children: List[Hierarchical[T]] = List()
}

// Nodes that aren't root nodes will have parents specified by ctor
class NonRootNode(override val parents: List[Hierarchical[_]]) 
  extends Hierarchical[NonRootNode] {}

// Roots will have no way to update their parents.
class Root extends Hierarchical[NonRootNode] {
  final override val parents = Nil
}

这是一个带有一些测试的小驱动程序:Ideone it

点赞