Scala:将自身声明为变量的类
我正在尝试在 scala 中创建一个二叉树,并且需要为其创建一个方法,因此我正在尝试在处理子级和父级的类中创建函数。 我想让父级成为一棵树,以便我可以在另一个名为 getPath 的函数中递归调用它,但我无法在 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 并且它会起作用,但如果你这样做,我就无法递归调用它。 任何人都可以帮助我或有其他方法来获取树的父母吗?
I'm trying to make a binary tree in scala and need to make a method for it so I'm trying to make functions inside the class that deals with children and parent.
I want to make the parent a Tree so that I can recursively call it in another function called getPath but I can't create a Tree inside the Tree class.
this is the code:
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())
}
I can set the T to Any and it'll work but then I can't recursively call it if you do.
Can anyone help me or has another way to get a tree's parent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
稍微清理一下你的代码,我得到:
这无法编译:
类型参数
T
出现在生成的类型中(父级的 getter)并且由该接口消耗(父级的设置器)。因此,它必须是不变的:Cleaning up your code a little, I get to:
This fails to compile with:
The type parameter
T
appears in types produced (getter for parent) and consumed (setter for parent) by this interface. Accordingly, it must be invariant: