Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use `case object` with a type parameter?

Tags:

scala

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.

like image 685
Abe Voelker Avatar asked Feb 23 '15 18:02

Abe Voelker


1 Answers

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.

like image 79
colevk Avatar answered Oct 19 '22 03:10

colevk