0

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.}

  • The error I am getting is ```value > is not a member of type parameter B``` – Muralitharan Perumal Jul 21 '19 at 09:31
  • 2
    This has nothing to do with co/contravariance, it's saying you can't compare something of type `A` with something of type `B` when they can be any types (except `B` is a supertype of `A`). E.g. they could both be `Object` and you can't compare `Object`s. – Alexey Romanov Jul 21 '19 at 09:36
  • @AlexeyRomanov Thanks for the explanation. I am able to compare the objects by doing this: ```def insert[B >: A <% Ordered[B]](x: B): TreeInterface[B]``` – Muralitharan Perumal Jul 21 '19 at 10:01
  • 3
    `[B >: A : Ordering]` (search for "context bounds") is the more general version, unfortunately then you need to add an import to make the operators available. – Alexey Romanov Jul 21 '19 at 10:13

0 Answers0