Reputation: 610
I am pretty new to Scala and am experimenting with case classes and context bounds. In this case, I am trying to create a simple search tree based on case classes with the code below. I want to understand why I cannot use one of my defined case classes as a default constructor parameter to another case class. Why do I get the "No implicit Ordering defined for A" error?
object FunWithBST extends App {
abstract class Tree[A](implicit ord: Ordering[A]) {
import ord._
def insert(value: A): Tree[A] = this match {
case BST(root) => BST(root.insert(value))
case Sentinel() => Node(l = Sentinel[A], v = value, r = Sentinel[A])
case Node(l, v, r) if (value < v) => Node(l.insert(value), v, r)
case Node(l, v, r) if (value > v) => Node(l, v, r.insert(value))
}
}
/* Following line gets the error:
No implicit Ordering defined for A.
case class BST[A: Ordering](root: Tree[A] = Sentinel[A]) extends Tree[A]
^
*/
case class BST[A: Ordering](root: Tree[A] = Sentinel[A]) extends Tree[A]
case class Node[A: Ordering](l: Tree[A], v: A, r: Tree[A]) extends Tree[A]
case class Sentinel[A: Ordering] extends Tree[A]
}
I'm sure there is a good reason for it, but I'm unclear as to why the error occurs, especially when defining the case class like this seems to work all right:
case class BST[A: Ordering](root: Tree[A]) extends Tree[A] {
def this() = this(root = Sentinel[A])
}
Please keep in mind that I'm experimenting to learn the language, so "Why don't you just do this..?" replies, while still helpful for learning, won't really answer the question. I want to know why the compiler is complaining.
Upvotes: 0
Views: 344
Reputation: 297155
Default values are created at the definition site, not the usage site -- it couldn't have been any other way. At the point you are defining BST
, you have no idea what A
will be, so you don't have an Ordering[A]
.
Upvotes: 1