I'm currently learning Scala, and wanted to replicate this Haskell algebraic data type:
data Tree = Empty
| Leaf Int
| Node Tree Tree
This is what I came up with in Scala:
sealed trait Tree[T]
case class Empty[T]() extends Tree[T]
case class Leaf[T](value: T) extends Tree[T]
case class Node[T](left: Tree[T], right: Tree[T]) extends Tree[T]
However, someone told me that I should use a case object
for Empty
, which I suppose is true since it doesn't take parameters - but then again it does require a type parameter.
I tried the following but none of them compile:
case object Empty[T] extends Tree[T]
case object Empty extends Tree[T]
case object Empty extends Tree
So I'm wondering if there a way to use case object
in this instance or not.
A singleton can't be generic because there's only one of them. If you want Tree
to be covariant (i.e. Tree[Int]
is a subtype of Tree[Any]
), then you can define the types as
sealed trait Tree[+T]
case object Empty extends Tree[Nothing]
Otherwise, leave it as a case class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With