2010-05-24 4 views
1

스칼라에서 이진 트리를 만들려고 노력 중이므로이 메서드를 만들어야 자식과 부모를 다루는 클래스 내부에서 함수를 만들려고합니다. 부모를 Tree로 만들어서 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를 설정하고 그것을 작동합니다하지만 당신이 경우에 나는 재귀 적으로 호출 할 수 없습니다 : 이 코드입니다. 누구나 나를 도와 줄 수 있나요? 아니면 나무의 부모를 얻는 다른 방법이 있습니까?

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

이 함께 컴파일에 실패 :

답변

5

코드를 정리 좀, 내가 얻을

tree-parent.scala:1: error: covariant type T occurs in contravariant position in type Tree[T] of parameter of setter parent_=

T이 (부모 게터) 생산과 소비 유형에 표시되는 형식 매개 변수 (부모 용의 setter)를이 인터페이스로 사용합니다. 따라서 불변 상태 여야합니다 :

case class Tree[T] 
+0

고맙습니다. 당신이했던 방식대로 내 아마추어 코드를 세련시키는 방법에 놀랐습니다. 언젠가 나는 똑같은 일을 할 수 있기를 바랍니다. 고맙습니다! – FireDragonMule

관련 문제