Scala 的Ordered
trait 被贬低了,所以我们必须使用Ordering
. 我试图重写我的 BST 类以使用Ordering
并得到一个编译错误。谁能解释一下如何Ordering
正确使用Nothing
。这是我的代码:
abstract sealed class Tree[+A: Ordering] {
def value: A
def left: Tree[A]
def right: Tree[A]
def isEmpty: Boolean
/**
* Time - O(1)
* Space - O(1)
*/
def mkTree(v: A, l: Tree[A] = Leaf, r: Tree[A] = Leaf): Tree[A] =
Branch(v, l, r)
/**
* Fails with message.
*/
def fail(s: String): Nothing =
throw new NoSuchElementException(s)
}
case object Leaf extends Tree[Nothing] {
def value: Nothing = fail("Empty tree.")
def left: Tree[Nothing] = fail("Empty tree.")
def right: Tree[Nothing] = fail("Empty tree.")
def isEmpty: Boolean = true
}
case class Branch[A: Ordering](value: A, left: Tree[A], right: Tree[A]) extends Tree[A] {
def isEmpty: Boolean = false
}
编译时我得到以下信息:
Tree.scala:21: error: No implicit Ordering defined for Nothing.
case object Leaf extends Tree[Nothing] {
^
one error found
我曾经写过这个类abstract class Tree[+A <% Ordered[A]]
,它工作得很好。