Scala:一个声明自己为变量的类

时间:2010-05-24 06:02:38

标签: scala path tree types covariance

我正在尝试在scala中创建一个二叉树,并且需要为它创建一个方法,所以我正在尝试在处理子项和父项的类中创建函数。 我想让父树成为一个树,以便我可以在另一个名为getPath的函数中递归调用它,但我不能在Tree类中创建一个Tree。 这是代码:

case class Tree[+T](value: T, left: Option[Tree[T]], right: Option[Tree[T]]) {
   var parent: Tree[T] = null

   //method for setting the parent of tree.
   //this method returns the parent TREE instead of the parent value
   //so if you want to use it to find the value, you need to get the parent.value
   def setParent(tree: Tree[T]) {
 parent = tree
   }

   //method for returning the parent
   //the parent is a tree so you have to .value it to get the root
   def getParent(): Tree[T] = parent

   //setting parents of left child and right child if they are not empty trees
   if(left != None) {
      left.get.setParent(this)
   }
   if(right != None) {
      right.get.setParent(this)
   }
}

def getPath[T](tree: Tree[T]):List[T] = {
   if(tree.getParent == null) List(tree.value)
   List(tree.value)++getPath(tree.getParent())
}

我可以将T设置为Any并且它可以工作但是如果你这样做我就不能递归调用它。 任何人都可以帮助我,或者有另一种方法来获得树的父母吗?

1 个答案:

答案 0 :(得分:5)

稍微清理你的代码,我得到:

case class Tree[+T](value: T, left: Option[Tree[T]], right: Option[Tree[T]]) {
  @reflect.BeanProperty   
  var parent: Tree[T] = null

  //setting parents of left child and right child if they are not empty trees
  Seq(left, right).flatten.foreach(_.setParent(this))
}

object Tree {
  def getPath[T](tree: Tree[T]):List[T] = List(tree.value) ++
    (if(tree.getParent == null) 
      Nil
    else
      getPath(tree.getParent()))
}

无法编译:

  

tree-parent.scala:1:错误:协变类型T出现在setter parent _ =

参数类型Tree [T]中的逆变位置

类型参数T出现在由此接口生成的类型(父级的getter)和消耗的(父级的setter)中。因此,它必须是不变的:

case class Tree[T]