I am trying to figure out the best way to implement a polymorphic tree:
trait Tree[A]
case object Void extends Tree[A] // does not compile
case class Node[A](left: Tree[A], key: A, right: Tree[A]) extends Tree[A]
Surely I can change Void from an object to a class, or I can have it extend Tree[Any], but I was wondering what would be the textbook implementation of this Tree in Scala. Thank you!
Treecovariant(then
Voidis a subtype ofTree[A]for anyA)Treeinvariant and then makeVoida classObjects (and values generally) can't be polymorphic in Scala (and JVM).
Making
VoidextendTree[Any]is incorrect. ThenVoidisn't a subtype ofTree[A].In principle, if you can perform all calculations at compile time, then you can lift your algebraic data type to the type level making
Treea type class