如何使用无类型约束专门化特征?

时间:2016-11-03 16:04:34

标签: scala traits type-constraints

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

我正在尝试创建一个特征Hierarchical,它基本上描述了图形中的顶点 - 任何可以有父母列表和子列表的对象。

更具体地说:

  • 1) A Hierarchical可能有也可能没有父母。

  • 2)如果确实如此,则父母为Hierarchical

  • 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类型,但我如何专注于此?

1 个答案:

答案 0 :(得分:1)

在做了一些头脑风暴之后,我发现父母的类型不需要指定 - 它们可以是一些任意的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