In the code shown below, how can I convert EmptyTree
to object (Singleton) ?
trait Tree[T] {
def contains(num: T): Boolean
def inc( num: T )
Let me detalize Alexey's answer. Here is full implementation with some code style improvements:
First define your trait with aknowledgment of its covariance:
trait Tree[+T] {
def contains[U >: T : Ordering](num: U): Boolean
def inc[U >: T : Ordering](num: U): Tree[U]
}
Next define your subtype-of-all-trees object
case object EmptyTree extends Tree[Nothing] {
def contains[U >: Nothing : Ordering](num: U): Boolean = false
def inc[U >: Nothing : Ordering](num: U): Tree[U] =
DataTree(num, EmptyTree, EmptyTree)
override def toString = "."
}
Now change your general case implementation:
case class DataTree[T: Ordering](x: T, left: Tree[T], right: Tree[T]) extends Tree[T] {
import Ordering.Implicits._
def contains[U >: T : Ordering](num: U): Boolean =
if (num < x) left.contains(x)
else if (num > x) right.contains(x)
else true
def inc[U >: T : Ordering](num: U): Tree[U] =
if (num < x) DataTree(x, left.inc(num), right)
else if (num > x) DataTree(x, left, right.inc(num))
else this
override def toString = "{" + left + x + right + "}"
}
You could be a little bit frustrated since I replaced your Ordered
with Ordering
, but you should know that view bounds are deprecated