I am getting the following error:
else if(x > elem) new NonEmpty(x, left, right insert x)
I changed the covariance to contravariance type but didnt work
object TestTree extends App {
val t1 = new NonEmpty(100, new Empty, new Empty)
println(t1)
}
trait TreeInterface[+A] {
def data: A
def left: TreeInterface[A]
def right: TreeInterface[A]
def insert[B >: A](x: B): TreeInterface[B] // variance problem
}
class Empty extends TreeInterface[Nothing] {
def data: Nothing = throw new NoSuchElementException("empty tree")
def left: TreeInterface[Nothing] = throw new UnsupportedOperationException("left of empty tree")
def right: TreeInterface[Nothing] = throw new UnsupportedOperationException("right of empty tree")
def insert[B >: Nothing](x: B): TreeInterface[B] = new NonEmpty(x, new Empty, new Empty)
override def toString = "."
}
class NonEmpty[+A](val elem: A, val left: TreeInterface[A], val right: TreeInterface[A]) extends TreeInterface[A]{
def insert[B >: A](x: B): TreeInterface[B] = {
if(x < elem ) new NonEmpty(x, left insert x, right)
else if(x > elem) new NonEmpty(x, left, right insert x)
else this
}
override def toString = "{" + left + elem + right + "}"
}
Expected output: {.100.}