I'd like to be able to exhaustively match on the types for implementations of a sealed trait, something like in the example below. Ideally I'd like to avoid using reflection (TypeTags) and implicit conversions if possible. Is there any way to exhaustively match on the type of a sealed trait?
object DataTypes {
sealed trait StrFy {
def stringify: String
}
final case class StrFyString(s: String) extends StrFy {
def stringify = s
}
final case class StrFyInt(i: Int) extends StrFy {
def stringify = i.toString
}
def stringifyThings[T <: StrFy](values: T*): String = {
val label = T match {
case StrFyString => "string"
case StrFyInt => "integer"
// cases that don't extend StrFy cause a compile error
}
"The " + label + " values are: " + values.map(_.stringify.fold("")(_+", "+_))
}
def printStringified(): Unit = {
println(stringifyThings(StrFyString("foo"), StrFyString("bar"))) // should print: "the string values are: foo, bar"
println(stringifyThings(StrFyInt(1), StrFyInt(2), StrFyInt(3))) // should print: "the integer values are: 1, 2, 3"
}
}
stringifyThings(StrFyString("s"), StrFyInt(9))
? – jwvh