I found out two ways which I can do pattern matching on a shapeless coproduct. I also googled this subject and found this
import shapeless._
object ShapelessEx3 extends App {
case class Red()
case class Green()
case class Blue()
type Colors = Red :+: Green :+: Blue :+: CNil
val blue = Coproduct[Colors](Blue())
val green = Coproduct[Colors](Green())
printColor1(blue)
printColor2(green)
def printColor1(c: Colors) : Unit = {
(c.select[Red], c.select[Green], c.select[Blue]) match {
case (Some(_), None, None) => println("Color is red")
case (None, Some(_), None) => println("Color is green")
case (None, None, Some(_)) => println("Color is blue")
case _ => println("unknown color")
}
}
def printColor2(c: Colors) : Unit = {
c match {
case Inl(Red()) => println("color is red")
case Inr(Inl(Green())) => println("color is green")
case Inr(Inr(Inl(Blue()))) => println("color is blue")
case _ => println("unknown color")
}
}
}
But both the functions are very noisy like case (None, Some(_), None)
or Inr(Inr(Inl(Blue())))
. How can I so a simple pattern matching like
c match {
case Red() =>
case Green() =>
case Blue() =>
}